im a newbie in Hibernate and i'm learning Relational Mapping. I have a problem with the bidrectional OneToMany Relationship. I have two Classes: Person and Vehicle. I used the @JoinTable
Annotation to create a third Table person_vehicle
.
Problem: How to get all the data from the joinTable into a List. I want to show them in a tableview, but my question is what type the data of the joinTable has?
My Solution:
Query query = session.createNativeQuery("select * from person_vehicle");
List<Object[]> list = query.getResultList();
@Entity
public class Person {
@Id
Integer id;
String name;
@OneToMany(mappedBy = "person")
List<Vehicle> vehicleliste=new ArrayList<Vehicle>();
public void removeVehicle(Vehicle vehicle){
getVehicleliste().remove(vehicle);
vehicle.setPerson(null);
}
public void addVehicle(Vehicle vehicle) {
getVehicleliste().add(vehicle);
vehicle.setPerson(this);
}
public List<Vehicle> getVehicleliste() {
return vehicleliste;
}
public void setVehicleliste(List<Vehicle> vehicleliste) {
this.vehicleliste = vehicleliste;
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Person() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
@Entity
public class Vehicle {
@Id
Integer vid;
String name;
@ManyToOne
@JoinTable(name = "person_vehicle", joinColumns = @JoinColumn(name="vehicleid",referencedColumnName = "vid"),
inverseJoinColumns = @JoinColumn(name="personid",referencedColumnName = "id"))
Person person;
public Integer getVid() {
return vid;
}
public void setVid(Integer vid) {
this.vid = vid;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Vehicle() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Vehicle(Integer vid, String name) {
super();
this.vid = vid;
this.name = name;
}
@Override
public String toString() {
return "Vehicle [vid=" + vid + ", name=" + name + "]";
}
Use entityManager.createQuery("FROM Person p LEFT JOIN FETCH p.vehicleliste", Person.class).getResultList()
. This will give you all person entities along with their vehicles.