在Hibernate中从JoinTable检索所有记录



我是Hibernate的新手,正在学习关系映射。我对双向一对多关系有意见。我有两类:人和车。我使用@JoinTable注释创建了第三个表person_vehicle

问题:如何将joinTable中的所有数据获取到列表中。我想在表视图中显示它们,但我的问题是joinTable的数据类型是什么?

我的解决方案:

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 + "]";
}

使用entityManager.createQuery("FROM Person p LEFT JOIN FETCH p.vehicleliste", Person.class).getResultList()。这将为您提供所有个人实体及其车辆。

相关内容

  • 没有找到相关文章

最新更新