java - Hibernate中清除持久化状态对象失效
怪我咯
怪我咯 2017-04-18 10:17:40
0
1
368

调用session.clear()或者session.evict(obj)皆无法清除Hibernate中的持久化状态的对象

目前已知的情况是:

  1. 当主键使用identify策略时,session.save(person)调用完成后会发出INSERT语句

  2. 当主键使用increment策略时,不会发出INSERT语句,并且结果与预期一致

代码如下:

@Test
public void test1(){
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    
    Person person = new Person();
    person.setName("tom888");
    session.save(person);    //此处是否发出**INSERT**语句与主键策略有关
    
    session.evict(person);
//  session.clear();
    transaction.commit();
    session.close();
}

主键使用identify策略时,代码执行结果:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into Person (name, description) values (?, ?)

我期待的结果应该是数据不应该有任何变化才对,也不应该执行任何SQL语句,因为我调用了session.clear()或者session.evict(obj)时,person应该由持久化状态转为游离状态,期待您的回答!

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
Ty80

After some study, I found the problem, so ask and answer it yourself. I hope it can help other friends who are studying.
Cause: This problem is caused by the id generator strategy defined in XXX.hbm.xml in the persistence class. I used the identity strategy here. Using this strategy will cause the session.save() method to get When executed, an INSERT statement is issued immediately. No matter what state the object is in at this time, it will not affect the update of the database by this object. Solution:
The id generator strategy can use a strategy that does not rely on the database to generate primary keys.

Please see my analysis for details: Analysis of session.evict() and session.clear() failure artifacts caused by primary key strategy in Hibernate

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!