有没有办法减少与CriteriaQuery相关的样板代码量(在JPA 2.0中)? [英] Is there a way to reduce the amount of boiler-plate code associated with a CriteriaQuery (in JPA 2.0)?

查看:162
本文介绍了有没有办法减少与CriteriaQuery相关的样板代码量(在JPA 2.0中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢类型安全 CriteriaQuery 带来了JPA 2.0,但它也带来了一些样板代码。例如,假设我有一个名为NamedEntity的实体,它只有一个id和一个名为name的String字段(假设它将唯一约束设置为true)。以下是NamedEntityManager的外观:

I love the type safety CriteriaQuery brings ing JPA 2.0 but it also brings a bit of boiler-plate code. For example, let say I have an entity called NamedEntity, which simply has an id and a String field called "name" (assume it has the unique constraint set to true). Here's what the NamedEntityManager might look like:

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对象?

Is there a way to condense the code in order to avoid copying/pasting the same lines of code into each query method? Perhaps somehow reuse the CriteriaQuery object?

推荐答案

似乎没有办法减少代码量。我想必须牺牲一些东西以获得类型安全。

It seems there's no way to reduce the amount of code. I guess something had to be sacrificed to gain type safety.

这篇关于有没有办法减少与CriteriaQuery相关的样板代码量(在JPA 2.0中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆