java findall方法_使用Java泛型进行JPA findAll()查询和WHERE子句

因此,经过10年的休整,我将回到Java并尝试使用JPA和Java泛型.我已经基本上创建了一个基于泛型的findAll(其他)JPA查询

SELECT * FROM source WHERE other_id = other.id;

这是我要去的地方.它有效,但我想知道是否有更好,更清洁的方法来做到这一点.使用ManagedType很难,而且没有太多完整的文档或简单的例子.

我决定尽可能保持我的代码通用(没有双关语)所以我使用JPA2.

这是所有实体类的根.我可能不需要它,但它阻止我有基本的错误.

import java.io.Serializable;

public abstract class DomainObject implements Serializable {

private static final long serialVersionUID = 1L;

public abstract void setId(Long id);

public abstract Long getId();

}

这是抽象的DAO类.我为实现类扩展了这个,因为我需要更具体地做其他活动 – 主要是确保加载延迟集.

public abstract class GenericDAOImpl implements GenericDAO {

private Class type;

@PersistenceContext

protected EntityManager entityManager;

public GenericDAOImpl(Class type) {

super();

this.type = type;

}

... save and delete classes go here

@Override

public List findAll(T2 where) {

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(type);

Root rootQuery = criteriaQuery.from(type);

if (where != null) {

EntityType entity = entityManager.getMetamodel().entity(type);

SingularAttribute super T, ?> attribute = null;

for (SingularAttribute super T, ?> singleAttribute: entity.getSingularAttributes()) {

// loop through all attributes that match this class

if (singleAttribute.getJavaType().equals(where.getClass())) {

// winner!

attribute = singleAttribute;

break;

}

}

// where t.object = object.getID()

criteriaQuery.where(criteriaBuilder.equal(rootQuery.get(attribute), where));

}

criteriaQuery.select(rootQuery);

TypedQuery query = entityManager.createQuery(criteriaQuery);

// need this to make sure we have a clean list?

// entityManager.clear();

return query.getResultList();

}

有什么建议么?如果有的话,我想要这个,所以其他人可以利用它.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值