JPA @ManyToOne 两张表

JPA @ManyToOne Two Tables

我有两个 table 学生和 Student_Pseudo。
伪可以归因于一个或多个学生。

学生包含

* Student_code 
* Student_login 

Student_Pseudo 包含

* Stu_code 
* Pseudo 

Stu_code 是 Student_code

的外键

我想使用@ManyToOne 关系在学生实体中获取伪,但它不起作用

@ManyToOne(optional = false)
    @JoinColumn(name="STU_CODE", referencedColumnName="STUDENT_CODE", nullable=false)
    private Pseudo pseudo;

当我得到 Students 时,Pseudo 总是 null !!!

好吧,这有点迂回,但它是我想到的第一件事,它确实有效。你说你需要获取学生伪造,所以在 Student 中添加了 Set。它应该是 EmbeddableCollection,因为我没有看到您在 student_pseudo 中引用任何主键。外键由父实体创建,您只需将其命名为JoinColumn。其他一切都是多余的。

@Entity
public class Student {
    @Id private int studentCode;
    private String studentLogin;
    @ElementCollection(targetClass=StudentPseudo.class)
    @CollectionTable(joinColumns={@JoinColumn(name="stu_code")})
    private Set<StudentPseudo> pseudos = new HashSet<>();


@Embeddable
public class StudentPseudo {
    private String pseudo;

也许您的问题在于获取它。

tx.begin();
Student student = new Student();
student.setStudentCode(1);
StudentPseudo studentPseudo1 = new StudentPseudo();
studentPseudo1.setPseudo("ps1");
student.getPseudos().add(studentPseudo1);
StudentPseudo studentPseudo2 = new StudentPseudo();
studentPseudo2.setPseudo("ps2");
student.getPseudos().add(studentPseudo2);

em.persist(student);
tx.commit();

em.clear();

List<Student> rl = em.createQuery("select distinct s from Student s left join fetch s.pseudos", Student.class).getResultList();

System.out.println(rl.get(0) + Arrays.toString(rl.get(0).getPseudos().toArray()));

这给出了

Hibernate: select distinct student0_.studentCode as studentC1_1_, student0_.studentLogin as studentL2_1_, pseudos1_.stu_code as stu_code1_2_0__, pseudos1_.pseudo as pseudo2_2_0__ from Student student0_ left outer join Student_pseudos pseudos1_ on student0_.studentCode=pseudos1_.stu_code
model.Student@2e380628[model.StudentPseudo@2b8bd14b, model.StudentPseudo@5f13be1]

假设 Student_Pseudo 是 Student 和 Pseudo 之间的关系 table,有多种方法可以做到这一点,但最简单的是:

@ManyToOne(optional = false)
@JoinTable(
    name = "Student_Pseudo", 
    joinColumns = @JoinColumn(name = "PSEUDO"), 
    inverseJoinColumns = @JoinColumn(name="STU_CODE", referencedColumnName="STUDENT_CODE", nullable=false))
private Pseudo pseudo;

我终于找到了基于@Chris 回复的解决方案。感谢大家的帮助。

@ManyToOne(optional = false)
    @JoinTable(
        name = "Student_Pseudo", 
        joinColumns = @JoinColumn(name = "STU_CODE", nullable=false), 
        inverseJoinColumns = @JoinColumn(name="STU_CODE", nullable=false))
private Pseudo pseudo;