hibernate .discard()
时间: 2023-11-26 18:06:31 浏览: 84
The Hibernate `discard()` method is used to discard any changes made to the persistent state of a managed entity. This method is useful when you want to cancel any changes made to an entity without actually updating the database.
When the `discard()` method is called on an entity, Hibernate clears the current session's cache and detaches the entity from the session. Any changes made to the entity after it was loaded from the database are lost.
Example usage:
```java
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// Load an entity from the database
MyEntity entity = session.get(MyEntity.class, 1L);
// Modify the entity
entity.setName("New Name");
// Discard the changes made to the entity
session.evict(entity);
tx.commit();
session.close();
```
In the example above, the `discard()` method is called implicitly when `evict()` is called on the entity. This discards any changes made to the entity and detaches it from the session. The changes made to the entity are not persisted to the database.
阅读全文