Reputation: 10954
I have an entity that has a reference to another one like these:
class School {
private boolean used = false;
}
class Student {
@ManyToOne
private School school;
}
The attribute used
indicates that the School
entity is whether used, referenced or not. So when created, a School
entity should have used
false, but once a Student
makes a reference to it, the used
must be turned to true. Is there any automatically way to do this like triggers in database?
I try to use @PrePersist
and @PostPersist
on Student
entity like this but it doesn't work:
@PrePersist
public void prePersist(){
school.setUsed(true);
}
Thanks,
Upvotes: 0
Views: 292
Reputation: 21883
My thought is that School should also have a reverse list of students. i.e.
class School {
private List<Student> students;
}
So when the school is loaded, you can easily access the list of students. Then finding out if a school is being used becomes very simple. You will not longer need a boolean flag, just this:
public boolean hasStudents() {
return students.size() > 0;
}
Upvotes: 2
Reputation: 1475
One way is to write a trigger on the insert, update of Student table, which will check if someone is holding the foreign key reference to school and you will have to check for all schools here. Also map your used variable to a column in School table. If any student is holding a reference, than make the column true and call a refresh from your application layer.
On the second thought, check if this is possible. When ever you need the logic for used variable, see that if you can write an HQL and using that HQL check if that particular school is currently getting used by any of the Student. This I think is a cleaner approach, but finally it's a call based on requirements :)
Upvotes: 1
Reputation: 2651
Additionally you need to define the CascadeType. See the example below:
class Team {
@OneToMany(mappedBy="team", cascade = CascadeType.ALL)
Set players;
}
class Player {
@ManyToOne
Team team;
}
Upvotes: 0