How to delete multiple records in Hibernate?
You can delete multiple records in Hibernate by using HQL (Hibernate Query Language) or by using the Criteria API.
The syntax for deleting multiple data using HQL is as follows:
String hql = "delete from EntityName where condition";
Query query = session.createQuery(hql);
query.executeUpdate();
EntityName is the name of the entity class, while condition is the criteria for the data to be deleted.
Here is an example code using Criteria API to delete multiple records:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaDelete<EntityName> criteriaDelete = builder.createCriteriaDelete(EntityName.class);
Root<EntityName> root = criteriaDelete.from(EntityName.class);
criteriaDelete.where(builder.equal(root.get("propertyName"), value));
session.createQuery(criteriaDelete).executeUpdate();
“In this case, EntityName refers to the name of the entity class, propertyName refers to the property name within the entity class, and value represents the value of the data property to be deleted.”
It is important to note that when using the above method to delete data, make sure to have enabled transactions before deleting the data.