Issue
In a Model I have:
public class House {
....
....
@OneToMany
@Nullable
private List<Person> people;
When running the Spring Boot application, I will see thee tables created. One for the House
model, one for the Person
and another one, automatically generated pivot table to keep relationship information House
and Person
.
My question is: what If I wanted to add a created_at
field onto the rows of the pivot table, so that for each association of House
to Person
I'd be able to tell when it was created.
I could not find a way to do that. What am I missing?
Solution
You should create an additional entity for the join table (House_Person). Inside of the new entity you declare the additional fields you need like created_at. Lastly you only need to link your both entitys to the new entity with @ManyToOne:
House_Person Entity:
@Entity
@Table(name = "HOUSE_PERSON")
public class HousePerson {
...
private Person person;
private House house;
// additional fields
private Date created_at;
...
private Person person;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "PERSON_ID")
public Person getPerson() {
return person;
}
private House house;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "HOUSE_ID")
public House getHouse() {
return house;
}
}
Have a look at this example here I hope that describes it well: codejava.net/hibernate-many-to-many-association-with-extra-columns-in-join-table-example
Answered By - anme98
Answer Checked By - Katrina (JavaFixing Volunteer)