[英]how to spring jpa hibernate create Entity that has many to one but without foreign key
I got two tables that has the many to one relationship, but they do not have a foreign key.我有两个具有多对一关系的表,但它们没有外键。 Like the
Student
are many, and the Teacher
is the one,就像
Student
很多,而Teacher
是一个,
the entities for example:实体例如:
@Entity
@Table(name = "student")
class Student {
@Column(name = "TeacherName")
private String teacherName;
@ManyToOne
private Teacher teacher
}
@Entity
@Table(name = "teacher")
class Teacher {
private String name;
}
When I query the students, the sql is :当我查询学生时,sql 是:
select * from Student as st INNER JOIN Teacher as tcr ON st.TeacherName = tcr.name;
I found the @ManyToOne
can not work and it looks like it needs a foreign key.我发现
@ManyToOne
不能工作,看起来它需要一个外键。 The table can not provide such though.表不能提供这样虽然。
Can someone tell me how to configure the entity?有人能告诉我如何配置实体吗?
You would have to use the following mapping:您必须使用以下映射:
public class Teacher {
@OneToMany(mappedBy = "teacher")
private Set<Student> students;
@Column(name = "name")
private String name;
}
public class Student {
@ManyToOne
@JoinColumn(name = "teacherName", referencedColumnName = "name")
private Teacher teacher;
}
Then in HQL:然后在 HQL 中:
select s from Student s INNER JOIN s.teacher t where t.name = :name
Alternatively If you want to stay with your current mapping and then you would need to use the 'old' style of join in hql to achieve joining by non-foreign-key columns:或者,如果您想保留当前的映射,那么您需要使用 hql 中的“旧”连接样式来实现非外键列的连接:
select s from Student s, Teacher t where t.name = s.teacherName and t.name = :name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.