10---Three states and state transition relationships of Hibernate persistent objects

Three states and state transition relationships of Hibernate persistent objects

1. Three states of persistent objects
    First review 2 concepts: persistent object PO and OID
    PO = POJO + hbm mapping configuration
     write rules
 
  
必须提供无参数 public 构造器
所有属性 private 提供 publicgettersetter方法
必须提供标识属性,与数据表中主键对应 ,例如 Customer id属性 
PO类属性应尽量使用基本数据类型的包装类型(区分空值)  例如 int --- Integer  long--- Long 
不要用final修饰(将无法生成代理对象进行优化)
     OID refers to the attribute in the PO class corresponding to the primary key in the data table, such as the Customer class id attribute 
     Hibernate framework uses OID to distinguish different PO objects 
          * For example, there are two PO objects in memory, as long as they have the same OID, Hibernate considers the same object 
* Hibernate does not allow caching of two different objects with the same OID

     ①Transient state (temporary state, free state): There is no persistent identifier OID, and the object has not been associated with the Hibernate Session. It is considered to be in the transient state, and the lost reference will be recycled by the JVM
    ②Persistent state: There is a persistent identifier OID, which is associated with the current session, and the associated session is not closed, and the transaction is not committed 
     ③Out -of-control state (offline state, free state): There is a persistent identifier OID, but it is not associated with the current session, and the change of the out-of-control state can not be detected by hibernate

    Distinguish three states: judging whether the object has an OID, judging whether the object is associated with the session (referenced by the first-level cache)
 
   
// 获得Session
Session session = HibernateUtils.openSession();
// 开启事务
Transaction transaction = session.beginTransaction();
 
Book book = new Book(); // 瞬时态(没有OID,未与Session关联)
book.setName("hibernate精通");
book.setPrice(56d);
 
session.save(book);// 持久态(具有OID,与Session关联)
 
// 提交事务,关闭Session
transaction.commit();
session.close();
 
System.out.println(book.getId()); // 脱管态(具有 OID,与Session断开关联)

2. Persistent object state transition

     Transient state object: obtained through new
         Instantaneous -----> persistent save, saveOrUpdate (both sessions)
         Transient ----->     Detachable book.setId(1) Set OID for transient object

     ②Persistent object: obtained through get/load, Query query
持久----->瞬时    delete  (被删除持久化对象 不建议再次使用 )
持久----->脱管    evict(清除一级缓存中某一个对象)、close(关闭Session,清除一级缓存)、clear(清除一级缓存所有对象 ) 

    脱管态对象 无法直接获得
脱管----->瞬时    book.setId(null); 删除对象OID 
脱管----->持久    update、saveOrUpdate、 lock(过时) 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324421423&siteId=291194637