【问题标题】:how to spring jpa hibernate create Entity that has many to one but without foreign key如何让jpa休眠创建具有多对一但没有外键的实体
【发布时间】:2017-02-08 06:51:22
【问题描述】:

我有两个具有多对一关系的表,但它们没有外键。 就像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 不起作用,它看起来需要一个外键。但是该表无法提供此类信息。

谁能告诉我如何配置实体?

【问题讨论】:

  • 您需要 Hibernate 查询吗?
  • 请检查答案@yang yang
  • 你为什么不检查答案?

标签: java spring hibernate jpa orm


【解决方案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

【讨论】:

  • 非常感谢。抱歉,因为其他更重要的工作阻碍了我,所以迟到了评论。
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多