in jpa/hibernate, the @softdelete annotation allow to not physicaly delete a row from the database. But what is the annotation to use for selecting only rows that are not soft deleted ?
Assistant
In JPA and Hibernate, there isn’t a built-in @SoftDelete annotation. However, soft deletes are commonly implemented by adding a boolean isDeleted (or similarly named) column to your entity, which marks whether a row is considered deleted.
To select only those rows that are not soft deleted, you would typically use a combination of a filter or a query method in your repository.
Example Implementation
User
yes there is @SoftDelete annotation since version 6.4 of Hibernate
Assistant
Apologies for the oversight! You are correct that starting from Hibernate 6.4, there's a built-in annotation that simplifies the implementation of soft delete functionality.
User
great, and do you know how to retrieve the deleted entities ?
Assistant
User
thanks
Assistant
You're welcome! If you have any more questions about JPA, Hibernate, or anything else, feel free to ask. Happy coding!
Entity Definition:
java
import javax.persistence.*;
@Entity
@Table(name = "my_entity")
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "is_deleted", nullable = false)
private boolean isDeleted = false;
// Getters and Setters
}
Using a JPQL or Criteria Query:
When querying the data, you would include a condition to check for non-deleted rows:
java
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
public class MyEntityRepository {
@PersistenceContext
private EntityManager entityManager;
public List<MyEntity> findAllActive() {
TypedQuery<MyEntity> query = entityManager.createQuery(
"SELECT e FROM MyEntity e WHERE e.isDeleted = false", MyEntity.class);
return query.getResultList();
}
}
Using @Where Annotation with Hibernate:
If you prefer to always filter for non-deleted entities without specifying it in every query, you can use the @Where annotation provided by Hibernate:
java
import org.hibernate.annotations.Where;
@Entity
@Table(name = "my_entity")
@Where(clause = "is_deleted = false")
public class MyEntity {
//... Same as before
}
Summary
In summary, you typically handle soft delete functionality in Hibernate with a boolean field in your entity and apply query filters or use the @Where annotation to filter out soft-deleted entities when performing searches.
@SoftDelete
Using @SoftDelete
With this annotation, you can easily mark entities for soft deletion without manually adding the soft delete logic. Here's how you can work with it, including how to query only for non-deleted entities.
1. Entity with @SoftDelete
You would annotate your entity class with @SoftDelete to indicate that it should be treated as a soft deletable entity:
java
import org.hibernate.annotations.*;
import javax.persistence.*;
@Entity
@Table(name = "my_entity")
@SoftDelete
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Additional fields...
// Getters and Setters...
}
2. Selecting Non-Soft Deleted Rows
Hibernate provides automatic handling for selecting only those instances that are not marked as deleted. Therefore, you do not need to add any additional filtering logic, as Hibernate will handle it transparently.
For instance, the following JPQL will only fetch entities that are not soft deleted:
java
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
public class MyEntityRepository {
@PersistenceContext
private EntityManager entityManager;
public List<MyEntity> findAllActive() {
TypedQuery<MyEntity> query = entityManager.createQuery(
"SELECT e FROM MyEntity e", MyEntity.class);
return query.getResultList();
}
}
In this case, the findAllActive() method will only return instances of MyEntity that are not soft deleted.
Differences from Manual Implementation
Using @SoftDelete simplifies your code because:
You avoid having to manually add a boolean field for soft deletion.
You don't need to include filters in your queries each time.
Hibernate manages the state of the soft-deleted entities for you, ensuring consistent behavior across your application.
Conclusion
With Hibernate 6.4 and the introduction of the @SoftDelete annotation, implementing soft deletes is much more straightforward. You just annotate your entity, and Hibernate takes care of the rest, allowing you to focus on your application’s logic rather than the persistence intricacies.
Yes, in Hibernate 6.4 and later, if you want to retrieve soft-deleted entities that you have annotated with @SoftDelete, you can do so by using the @EntityGraph or by explicitly allowing retrieval of deleted entities.
Retrieving Deleted Entities
Using @EntityGraph with Hibernate:
Hibernate provides the ability to bypass the soft delete filter by configuring an @EntityGraph. You can define an EntityGraph that allows fetching of soft-deleted entities.
Here's how you can define and use it:
java
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
public class MyEntityRepository {
@PersistenceContext
private EntityManager entityManager;
public List<MyEntity> findAllIncludingDeleted() {
// Get the EntityGraph that includes deleted entities
EntityGraph graph = entityManager.createEntityGraph(MyEntity.class);
graph.addAttributeNodes("name"); // Adjust based on your entity's attributes
TypedQuery<MyEntity> query = entityManager.createQuery("SELECT e FROM MyEntity e", MyEntity.class);
query.setHint("javax.persistence.fetchgraph", graph);
return query.getResultList();
}
}
Using Session and getDeleted() with Hibernate:
As of the latest version, you can use the Session API to explicitly query for soft-deleted entities by using the CriteriaBuilder with CriteriaQuery. You can also utilize the getDeleted() method in Hibernate.
In summary, with Hibernate and the @SoftDelete annotation:
To retrieve soft-deleted entities, you can use entity graphs or query them explicitly by considering the deletion status.
The soft-deleted entities can be accessed transparently without excessive manual handling due to Hibernate's built-in capabilities.
To ensure proper results, always refer to the latest documentation for the exact version of Hibernate you're using, as methods and features might undergo changes or improvements.