如何弹出jpa hibernate创建具有多对一但没有外键的实体

时间:2017-02-08 06:51:23

标签: java spring hibernate jpa orm

我有两个具有多对一关系的表,但它们没有外键。   就像Student很多,而Teacher就是那个,

实体例如:

@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;
}

当我查询学生时,sql是:

select * from Student as st INNER JOIN Teacher as tcr ON st.TeacherName = tcr.name;

我发现@ManyToOne无法正常工作,看起来它需要一个外键。该表不能提供这样的。

有人可以告诉我如何配置实体吗?

1 个答案:

答案 0 :(得分:1)

您必须使用以下映射:

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;

}

然后在HQL中:

select s from Student s INNER JOIN s.teacher t where t.name = :name 

<强>替代地 如果你想继续使用当前的映射,那么你需要在hql中使用'旧'连接样式来实现非外键列的连接:

select s from Student s, Teacher t where t.name = s.teacherName and t.name = :name