[英]How to Use Multiple Join on Hibernate?
I have these following Classes: 我有以下几个类:
class Person(){
@OneToMany(mappedBy="person")
private List<PersonRoles> roles;
}
class PersonRoles(){
@ManyToOne
@JoinColumn(name = "person_id", nullable = false)
private Person person;
@ManyToOne
@JoinColumn(name = "request_id")
private Request request;
}
class Request(){
@OneToMany(mappedBy="request")
private List<PersonRoles> roles;
}
Now I am going to fetch all person based on a given request id and his roles by using hibernate and inner join but my log is telling me that my table doesn't exist. 现在我将通过使用hibernate和内部联接基于给定的请求ID和他的角色来获取所有人,但是我的日志告诉我我的表不存在。 This is my query so far: 这是我目前的查询:
sql = "SELECT p.* FROM person AS p INNER JOIN p.roles ON p.roles.personId = p.id
INNER JOIN request AS r ON p.roles.requestId = r.id AND p.roles.role like :item
AND r.id = :id";
query = session.createSQLQuery(sql);
query.addEntity(Person.class);
query.setParameter("item", "Members");
query.setParameter("id", id);
person = (Person) query.uniqueResult();
and this is what i received on the log: 这就是我在日志中收到的内容:
Table 'p.roles' doesn't exist
Did i forget some hibernate annotation? 我忘记了一些hibernate注释吗? or My query has something wrong? 或者我的查询有问题?
Brief reason 简要原因
your syntax of SQL is wrong 您的SQL语法错误
Detailed explanation 详细解释
here is the syntax of inner join example 这是内连接示例的语法
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
for multiple inner join 用于多个内部联接
SELECT *
FROM table1
INNER JOIN table2
ON table1.primaryKey=table2.table1Id
INNER JOIN table3
ON table1.primaryKey=table3.table1Id
but you have used INNER JOIN p.roles
there should be a table name after the INNER JOIN, not a column name. 但是你使用了INNER JOIN p.roles
,在INNER JOIN之后应该有一个表名,而不是列名。
that's why you got an error, moreover, use HQL instead of SQL in hibernate it is a good practice. 这就是为什么你得到一个错误,而且,在hibernate中使用HQL代替SQL这是一个很好的做法。
happy coding! 快乐的编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.