Hibernate中通过HQL/JPQL查询的方式实现动态数据获取

1. JPQL查询

Employee employee = entityManager.createQuery(
    "select e " +
    "from Employee e " +
    "left join fetch e.projects " +
    "where " +
    "    e.username = :username and " +
    "    e.password = :password",
    Employee.class)
.setParameter( "username", username)
.setParameter( "password", password)
.getSingleResult();


2. Criteria查询

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery( Employee.class );
Root root = query.from( Employee.class );
root.fetch( "projects", JoinType.LEFT);
query.select(root).where(
    builder.and(
        builder.equal(root.get("username"), username),
        builder.equal(root.get("password"), password)
    )
);
Employee employee = entityManager.createQuery( query ).getSingleResult();


注意上述示例中 黑体的“fetch"用法。



你可能感兴趣的:(Hibernate中通过HQL/JPQL查询的方式实现动态数据获取)