Reputation: 1933
Looking for a solution to map multiple student_id
rows under the same class_id
, here is the table which has 3 fields:
integer id PRIMARY KEY
integer class_id;
integer student_id;
The table can have multiple rows under the same class_id
like this:
Table = 'class'
id class_id student_id
1, 1, 1
2, 1, 2
3, 1, 3
4, 2, 1
5, 3, 1
I'm trying to Map this into a Pojo so I can use it as follow:
List<UniClass> uniClasses = session.createQuery("FROM ClassOfStudent", ClassOfStudent.class).getResultList();
I'm trying to solve this problem by using @ElementCollection
Here is my attempt:
@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;
....
}
Any idea how to make this work?
Upvotes: 0
Views: 256
Reputation: 1933
The trick that made this possible is that eventually I mapped the @Id
of the class to be m_classId
although it's not really the primary key of the table in the DB.
@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;
...
}
Upvotes: 0