Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Saturday

JPA-(Java Persistence API) Tutorial-ManyToMany with extra fields

ManyToMany with extra fields

Imagine a Person entity that has a ManyToMany relationship with the Dog entity; every time that a dog is adopted
by a person the application should register the adoption date. This value must be stored in the relationship and not
an an attribute on person nor dog.
To handle this kind of situationwe use the "Associative Class" alias "Associative Entity" approach. With this

approach it is possible to store extra data when the ManyToMany relationship is created.

import java.util.List;
import javax.persistence.*;
@Entity
public class Person {
@Id
@GeneratedValue
private int id;
private String name;
@OneToMany(mappedBy = "person")
private List<PersonDog> dogs;
// get and set
}
import java.util.List;
import javax.persistence.*;
@Entity
public class Dog {
@Id
@GeneratedValue
private int id;
private String name;
@OneToMany(mappedBy = "dog")
private List<PersonDog> persons;
// get and set
}
The code above is using the @OneToMany relationship with the mappedBy option. Notice that there is no
@ManyToMany relationship between the entities, but there is an entity PersonDog that unite both entities.
Below is the PersonDog code:
import java.util.Date;
import javax.persistence.*;
@Entity
@IdClass(PersonDogId.class)
public class PersonDog {
@Id
@ManyToOne
@JoinColumn(name="person_id")
private Person person;
@Id
@ManyToOne
@JoinColumn(name="dog_id")
private Dog dog;
@Temporal(TemporalType.DATE)
private Date adoptionDate;
// get and set
}

In the code above you can see the relationships between PersonDog, Dog and Person, and an extra attribute to
store the adoption date. There is an id class to store the relationship ids named "PersonDogId":

import java.io.Serializable;
public class PersonDogId implements Serializable {
private static final long serialVersionUID = 1L;
private int person;
private int dog;
public int getPerson() {
return person;
}
public void setPerson(int person) {
this.person = person;
}
public int getDog() {
return dog;
}
public void setDog(int dog) {
this.dog = dog;
}
@Override
public int hashCode() {
return person + dog;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PersonDogId){
PersonDogId personDogId = (PersonDogId) obj;
return personDogId.dog == dog && personDogId.person == person;
}
return false;
}
}
One thing to notice here is that person and dog attributes must have the same name - "person" and "dog" here -
between the PersonDogId and PersonDog entities. It is how JPA works. More information about complex keys can

be found at earlier sections of this tutorial

NEXT


No comments:

Post a Comment