java EntityManager 通过 joinColumn 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12907921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EntityManager query by joinColumn
提问by kasavbere
I have a Login
entity and a Customer
entity. Login.username
is a foreign key in the customer table. Hence the following line in the Java Customer
POJO
我有一个Login
实体和一个Customer
实体。Login.username
是客户表中的外键。因此,Java Customer
POJO 中的以下行
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
private Login login;
My question is this: Is there a simple way to query the customer
table using username
? Or must I first fetch login
by username
and then customer
by login
?
我的问题是:有没有一种简单的方法可以customer
使用username
? 还是必须我第一次取login
的username
,然后customer
用login
?
Here is the JPA criteria query. And, yes, I would prefer to use criteria query.
这是 JPA 条件查询。而且,是的,我更喜欢使用标准查询。
public Customer getCustomerByUsername(String username) throws EntityNotFoundException {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Customer> criteriaQuery = criteriaBuilder.createQuery(Customer.class);
Root<Customer> root = criteriaQuery.from(Customer.class);
Path<String> path = root.<String>get("username");
criteriaQuery.where(criteriaBuilder.equal(path, username));
return entityManager.createQuery(criteriaQuery).getSingleResult();
}
The line Path<String> path = root.<String>get("username")
is throwing an exception saying that username ... is not present.
该行Path<String> path = root.<String>get("username")
抛出异常说username ... is not present.
回答by kasavbere
The correct solution with JPQL is
JPQL 的正确解决方案是
Query q = entityManager.createQuery("SELECT c FROM Customer c WHERE c.login.username = :username");
q.setParameter("username", username);
return (Customer) q.getSingleResult();
回答by ppeterka
Query q = entityManager.createQuery("SELECT c FROM Customer c JOIN Login l ON c.login=l WHERE l.username = :username");
q.setParameter("username",username);
List<Customer> customerList = q.getResultList();
There are a few tricks to keep in mind: this all is about the objects, and not the underlying DB. So the names represent classes, instances, and fields, and they are all CaseSensitive... The error you got meant that your Customer class didn't have a userName field - which is true, since Login has that... Sadly, I can't test it, but the logic and intentions should be clear.
有一些技巧需要牢记:这一切都与对象有关,而不是底层数据库。所以名称代表类、实例和字段,它们都是区分大小写的......你得到的错误意味着你的 Customer 类没有 userName 字段 - 这是真的,因为 Login 有......可悲的是,我无法测试,但逻辑和意图应该很清楚。