How can we add criteria to a SQL query in Hibernate?
In Hibernate, you can add criteria to a SQL query using the Criteria API or the Query Language (HQL). Below are examples of how to use both methods to add criteria to your queries.
The Criteria API allows you to build queries programmatically. Here’s how you can use it:
EntityManager
to execute the query.Here’s an example:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
public class CriteriaExample {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("your-persistence-unit");
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<YourEntity> cq = cb.createQuery(YourEntity.class);
Root<YourEntity> root = cq.from(YourEntity.class);
// Adding criteria
Predicate condition1 = cb.equal(root.get("fieldName"), "value");
Predicate condition2 = cb.greaterThan(root.get("anotherField"), 10);
cq.select(root).where(cb.and(condition1, condition2));
List<YourEntity> results = em.createQuery(cq).getResultList();
// Process results
results.forEach(System.out::println);
em.close();
emf.close();
}
}
HQL is similar to SQL but operates on the entity objects rather than the database tables. You can add criteria using WHERE
clauses.
Here’s an example:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;
public class HQLExample {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// HQL query with criteria
String hql = "FROM YourEntity e WHERE e.fieldName = :value AND e.anotherField > :threshold";
Query<YourEntity> query = session.createQuery(hql, YourEntity.class);
query.setParameter("value", "someValue");
query.setParameter("threshold", 10);
List<YourEntity> results = query.getResultList();
// Process results
results.forEach(System.out::println);
transaction.commit();
session.close();
sessionFactory.close();
}
}
Both methods allow you to add criteria to your queries effectively, and you can choose based on your preference or specific use case.