yang yang
yang yang

Reputation: 169

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,

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 :

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. The table can not provide such though.

Can someone tell me how to configure the entity?

Upvotes: 2

Views: 1702

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

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:

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:

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

Upvotes: 1

Related Questions