Home > Software engineering >  map a @OneToMany relationship using a string column as a key
map a @OneToMany relationship using a string column as a key

Time:06-20

Good Morning!

I would like to know if there is a way to map a @OneToMany relationship using a string column as a key. The database in SQL Server already has all the tables, but their relationship was not made by the id, but by values ​​of type string. Can anyone help me? Example:

student table with the fields name, phone, emailthe key of this table is the column "name"

class tablewith the fields name, date, discipline the key of this table is the column "name" that refers to "student name".

as I tried to do:

@Entity
public class Student {
  ...

  @OneToMany(mappedBy = "student")
  private List<Class> class = new ArrayList<>();
}

@Entity
public class Class{
  ...

  @ManyToOne
  @JoinColumn(name = "student_id")
  private Student student;
}

When I run it through H2, it creates a column with the students' id, but I would like it to map the data that is already in the database, because I can't change the data structure. Can someone help me?

CodePudding user response:

String is a valid type for an identifier. If you don't want an additional id column, you can map name as an identifier:

@Entity
public class Student {
  
  @Id
  @Column(name = "`name`")
  String name;
  
  @OneToMany(mappedBy = "student")
  private List<Class> class = new ArrayList<>();
  ...
}

For some databases name is a special keyword, if you use @Column(name = "`name`"), Hibernate will handle it correctly.

  • Related