我喜欢 JPA 2.0 带来的类型安全CriteriaQuery,但它也带来了一些样板代码。例如,假设我有一个名为 NamedEntity 的实体,它只有一个 id 和一个名为“name”的字符串字段(假设它的唯一约束设置为 true)。NamedEntityManager 可能如下所示:
public class NamedEntityManager
{
//inject using your framework
EntityManager entityManager;
//retrieve all existing entities of type NamedEntity from DB
public Iterable<NamedEntity> queryAll()
{
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<NamedEntity> query = builder.createQuery(NamedEntity.class);
return entityManager.createQuery(query).getResultList();
}
//retrieve a single entity of type NamedEntity from DB using specified name
public NamedEntity queryByName(String name)
{
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<NamedEntity> query = builder.createQuery(NamedEntity.class);
Root<NamedEntity> root = query.from(NamedEntity.class);
query = query.where(root.<NamedEntity>get("name").in(name));
//skipped the try/catch block for the sake of brevity
return entityManager.createQuery(query).getSingleResult();
}
}
有没有办法压缩代码以避免将相同的代码行复制/粘贴到每个查询方法中?也许以某种方式重用 CriteriaQuery 对象?