gpt4 book ai didi

sql - JPA,获取所有元素

转载 作者:行者123 更新时间:2023-12-04 14:29:20 27 4
gpt4 key购买 nike

我正在使用 JPA 并在此代码中从 DB 获取所有元素:

factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// read the existing entries and write to console
Query q = em.createQuery("select s from Supporter s");
List<Supporter> supportersList = new ArrayList<Supporter>();
supportersList = q.getResultList();

问题是如何以更优雅的方式获取数据,我的意思是没有 createQuery("select s from Supporter s");我记得有像 findAll 或 getAll 这样的方法在大小写“明确”并且我们不需要 native 查询时在 JPA 中使用。

最佳答案

您可以使用类型安全标准:

public List<Supporter> findAll() {
EntityManager em = factory.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Supporter> cq = cb.createQuery(Supporter.class);
Root<Supporter> rootEntry = cq.from(Supporter.class);
CriteriaQuery<Supporter> all = cq.select(rootEntry);
TypedQuery<Supporter> allQuery = em.createQuery(all);
return allQuery.getResultList();
}

关于sql - JPA,获取所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38336840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com