休眠:使用ElementCollection映射多行-单表无可嵌入

时间:2019-03-22 18:30:27

标签: hibernate hibernate-mapping

寻找一种在同一student_id下映射多个class_id行的解决方案,这是具有3个字段的表:

integer id PRIMARY KEY
integer class_id;
integer student_id;

该表可以在同一class_id下包含多个行,如下所示:

Table = 'class'
id  class_id  student_id 
1,    1,          1
2,    1,          2
3,    1,          3
4,    2,          1
5,    3,          1

我正在尝试将其映射到Pojo中,以便可以按以下方式使用它:

List<UniClass> uniClasses = session.createQuery("FROM ClassOfStudent", ClassOfStudent.class).getResultList();

我正在尝试使用@ElementCollection

解决此问题

这是我的尝试:

@Entity
@Table(name = "class")
public class ClassOfStudents{
   @Id
   @Column("id")
   private long m_id;

   @Column(name = "class_id")
   private long m_classId;

   @ElementCollection
   @CollectionTable(name = "class", joinColumns = @JoinColumn(name="class_id"))
   @Column(name = "student_id")
   private List<Long> m_studentIds;

   ....
}

有什么主意要怎么做吗?

1 个答案:

答案 0 :(得分:0)

使之成为可能的诀窍是,尽管实际上并不是数据库中表的主键,但最终我将类的@Id映射为m_classId

@Entity
@Table(name = "class")
public class ClassOfStudents implements Serializable
{
  @Id
  @Column(name = "class_id")
  private long classId;

  @ElementCollection(targetClass = Long.class, fetch = FetchType.EAGER)
  @CollectionTable(name = "class", joinColumns = @JoinColumn(name = "class_id"))
  @Column(name = "student_id", nullable = false)  
  private List<Long> m_studentIds;
...
}