Hibernate的查询方式有哪些?
Hibernate 是一个流行的 Java ORM(对象关系映射)框架,它提供了多种查询方式来从数据库中检索数据。以下是 Hibernate 中常用的几种查询方式:
HQL(Hibernate Query Language):
String hql = "FROM User WHERE age > :age";
Query query = session.createQuery(hql);
query.setParameter("age", 18);
List<User> users = query.list();
Criteria API:
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root).where(criteriaBuilder.gt(root.get("age"), 18));
List<User> users = session.createQuery(criteriaQuery).getResultList();
Native SQL 查询:
String sql = "SELECT * FROM users WHERE age > :age";
Query query = session.createNativeQuery(sql, User.class);
query.setParameter("age", 18);
List<User> users = query.getResultList();
JPQL(Java Persistence Query Language):
String jpql = "SELECT u FROM User u WHERE u.age > :age";
Query query = entityManager.createQuery(jpql);
query.setParameter("age", 18);
List<User> users = query.getResultList();
Named Queries:
@NamedQuery
注解定义,便于重用。@NamedQuery(name = "User.findByAge", query = "FROM User WHERE age > :age")
Query by Example (QBE):
User exampleUser = new User();
exampleUser.setAge(18);
Example<User> example = Example.of(exampleUser);
List<User> users = session.createCriteria(User.class).add(example).list();
这些查询方式各有优缺点,开发者可以根据具体的需求和场景选择合适的查询方式。