如何使用@ManyToMany 注释表获取数据?

How to get data with @ManyToMany annotated tables?

我的相关表格如下。 人 Table

  1. 编号
  2. 名字
  3. 姓氏

地点Table

  1. 编号
  2. 标题

Person_Location Table

  1. person_id
  2. location_id

我想要像这样获取人物和位置值..


编号 |姓名 |姓 |标题 |点

1 约翰 |阿达斯 |我的家 | 44,45
1 |约翰 |阿达斯 |兄弟的家 | 55,33

如何在休眠状态下获取用户及其位置?

// 亲自 class:

    @ManyToMany
    @JoinTable(name="Person_Location",
        joinColumns=
            @JoinColumn(name="person_id", referencedColumnName="ID"),
        inverseJoinColumns=
            @JoinColumn(name="location_id", referencedColumnName="ID")
        )
    public Set<Locations> getLocations() { return locations; }

// 所在位置:

    @ManyToMany(mappedBy="locations")
    public Set<Person> getPersons() { return persons; }

亲临现场class

@OneToMany(mappedBy="person")
    public Set<personLocations> getPersonLocation { return personLocations; }

地点class

@OneToMany(mappedBy="location")
    public Set<personLocations> getPersonLocation { return personLocations; }

亲自前往地点

 @ManyToOne
    @JoinColumn(name="person_ID")
    public Person getPerson() { return person; }

 @ManyToOne
    @JoinColumn(name="location_ID")
    public Location getlocation() { return location; }

试试这个:

你可以获得一个对象数组,你可以随意操作它们

String stringQuery="select p.id,p.name,p.surname,l.title,l.point from person p, location l,person_location pl where "
                + "p.id=pl.person_id and l.id=pl.location_id";
        Query query=entityManager.createNativeQuery(stringQuery);
        List<Object[]> result=query.getResultList();

稍后您可以通过result.get(i)[0]

获取人员ID

或者您可以创建一个自定义的 class,它将不是托管实体:

public class customPerson{
id | name | surname | title | point
private int id;
private String name;
private String surname;
private String title;
private String doube point;

//getters&setters

//constructors (required) one default ant one with all your attributes
public CustomPerson(){}
public customPerson(int id,...){
...
}

}

稍后在您的 Dao 中您可以通过自定义对象获得您想要的结果:

String stringQuery="select p.id,p.name,p.surname,l.title,l.point from person p, location l,person_location pl where "
                + "p.id=pl.person_id and l.id=pl.location_id";
        Query query=entityManager.createNativeQuery(stringQuery,CustomPerson.class);
        List<CustomPerson> result=query.getResultList();