我们什么时候需要从持久化上下文中分离实体?
答案 0 :(得分:1)
实体的分离意味着,hibernate不再具有对实体的访问权限。让我们看看使用下面的例子。
//Thid is where the entity is in transient State (Ther data is not saved, but initialized)
User user = new user
user.setName("User1");
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = (StandardServiceRegistryBuilder) new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = builder.build();
SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
user.setUserName("Hello There");//Here the data is in persistent state
session.save(user);
user.setUserName("Hello There Again");//Here also the data is in persistent state
user.setUserName("Hello There Again for second time");//Here also the data is in persistent state, but the hibernate will take the last update, if you see the query in log/console, you will find only one update query.
tx.commit();
session.close();
user.setUserName("Hello Again Final");//Since the session is closed, the data is not persisted, Here the entity is detached
factory.close();
StandardServiceRegistryBuilder.destroy(serviceRegistry);
关闭数据库后会发生实体的分离,通常在执行session.close()后发生。
有关工作流程的更多信息,请访问https://javabrains.io/courses/hibernate_run/lessons/Understanding-State-Changes