JPA @ManyToOne两个表

时间:2018-07-04 11:14:09

标签: java eclipselink jpa-2.0

我有两个表Student和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;

当我得到学生时,伪总是为空!!!

3 个答案:

答案 0 :(得分:0)

嗯,这是一个环形交叉路口,但这是我想到的第一件事,它确实起作用。您说您需要获取学生的伪造品,因此为此在Set中添加了Student。应该是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]

答案 1 :(得分:0)

假设Student_Pseudo是Student和Pseudo之间的关系表,可以通过多种方式进行,但是最简单的方法是:

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

答案 2 :(得分:0)

我终于找到了基于@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;