[英]How to use hibernate query on two tables (join table)?
I have these tables: cont(id_cont, user, pass) emp(emp_id, name, cont_id_cont (fk)) 我有这些表:cont(id_cont,user,pass)emp(emp_id,name,cont_id_cont(fk))
@Entity @Table(name = "emp", catalog = "", uniqueConstraints = { @UniqueConstraint(columnNames = "cont_id_cont") }) public class Emp implements java.io.Serializable{ private int id_emp; private ContUser contUser; private String name;
and 和
@Entity
@Table(name = "cont", catalog = "", uniqueConstraints = {
@UniqueConstraint(columnNames = "pass") })
public class Cont implements java.io.Serializable{
private int id_cont;
private String user;
private String pass;
private Set<Emp> empForCont = new HashSet<Emp>(0);
}
Now: I want this query: select cont.user, emp.name, emp.cont_id_cont from cont inner join emp on cont.id_cont= emp.cont_id_cont where cont.user = 'gbs04405'; 现在:我要查询:从cont.id_cont = emp.cont_id_cont上的cont内部连接emp中选择cont.user,emp.name,emp.cont_id_cont,其中cont.user ='gbs04405';
This style of accessing data is not what ORM
is intended for. 这种访问数据的方式不是
ORM
的目的。 If you are using Hibernate
, you should (usually) access data through objects. 如果您正在使用
Hibernate
,则(通常)应该通过对象访问数据。 To make this work, instead of embedding SQL like constraints, define relations @OneToMany
, @ManyToOne
, and/or @ManyToMany
between objects where necessary. 为了使这项工作有效,而不是像约束一样嵌入SQL,而是在必要时在对象之间定义关系
@OneToMany
, @ManyToOne
和/或@ManyToMany
。
In addition, you should consider using HQL
(or JPQL
) instead of pure SQL
, to achieve what you want. 另外,您应该考虑使用
HQL
(或JPQL
)代替纯SQL
来实现所需的功能。
It should be something like this: 应该是这样的:
SELECT e FROM Emp e JOIN e.contUser u WHERE u.user = :userstring
You can check here for further JPQL
syntax. 您可以在此处查看其他
JPQL
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.