gpt4 book ai didi

jpa - : getSingleResult, 或 getResultList JPA 哪个更好

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

我需要从表中检索单行,我对哪种方法更好感兴趣。
一侧getSingleResult专为检索单个结果而设计,但会引发异常。此方法是否对与 getResultList 相关的性能有好处?和

query.setFirstResult(0);
query.setMaxResults(1);

最佳答案

根据 Joshua Bloch 的 Effective Java:

Use checked exceptions for conditions from wich the caller can reasonably be expected to recover. Use runtime exceptions to indicate programming errors.



归功于来源: Why you should never use getSingleResult() in JPA
@Entity
@NamedQuery(name = "Country.findByName",
query = "SELECT c FROM Country c WHERE c.name = :name"
public class Country {
@PersistenceContext
transient EntityManager entityManager;

public static Country findByName(String name) {
List<Country> results = entityManager
.createNamedQuery("Country.findByName", Country.class)
.setParameter("name", name).getResultList();
return results.isEmpty() ? null : results.get(0);
}
}

关于jpa - : getSingleResult, 或 getResultList JPA 哪个更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500031/

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