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

时间:2016-06-06 15:21:21

标签: sql hibernate spring-mvc many-to-many

我的相关表格如下。 人员表

  1. id
  2. 名称
  3. 位置表

    1. id
    2. 标题
    3. Person_Location表

      1. person_id
      2. LOCATION_ID
      3. 我想得到像这样的人和位置值..

        id |名字|姓氏|标题|点

        1约翰| adas |我的家| 44,45
        1 |约翰| adas |兄弟的家| 55,33

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

3 个答案:

答案 0 :(得分:0)

//在Person类中:

    @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; }

答案 1 :(得分:0)

在人类

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

在位置课程

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

In personLocations

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

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

答案 2 :(得分:0)

试试这个:

你可以获得一个对象数组,你可以根据需要操作它们

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

或者您可以创建一个不属于托管实体的自定义类:

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();