Reputation: 21
I need to dynamically allocate value at creation time for an entity by fetching value from related table. Consider the below scenario where I have two classes - Student & Batch.
While inserting a new record in Student table at the time of creation, I need to set the field 'allocatedBatch' in Student table by fetching Batch for which 'Active' field is true from Batch table.(considering the fact that only one batch can be active at the given time)
And this has to be done dynamically. Please suggest me some best usage of hibernate to handle this.
Note - As this has to be done without using the respective service and repository class, looking for hibernate usage
Student.java
public class Student {
@Id
@GeneratedValue(Strategy = GeneratedType.Identity)
private Integer id;
private String name;
private Date DOB;
@ManyToOne
@JoinColumn(name = "Student_Batch", nullable=false)
private Batch allocatedBatch;
.....Getter and setter methods....
}
Batch.java
public class Batch {
@Id
@GeneratedValue(Strategy = GeneratedType.Identity)
private Integer id;
private String name;
private Date startDate;
@ColumnDefault("false")
private boolean Active;
@OneToMany(mappedBy = "allocatedBatch", cascade = {CascadeType.PERSIST, CascadeType.REMOVE)
private Set<Student> students;
.....Getter and setter methods....
}
Upvotes: 0
Views: 1465
Reputation: 804
I don't know your circumstances, but this sounds like you may need to rethink your design. However, I think using Event listener or Interceptor might do the trick. (If I understand this correctly)
Check out @PrePersist
annotation. JPA Callback
Upvotes: 0