JPQL manyToMany单向查询

时间:2015-06-25 11:04:54

标签: java many-to-many entity jpql jointable

我一直在寻找论坛和各地的单向manyToMany查询。我找到很多例子,但我无法根据自己的需要调整它们:(

我有2个实体类(动漫和用户)

Anime {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "anime_id")
    private Integer id;

    //Other fields etc.
}

User {
    @Id
    @ValidUsername
    @Column(name = "user_id")
    private String username;

    @ManyToMany()
    @JoinTable(name = "users_animes",
        joinColumns = @JoinColumn(name = "anime_id", referencedColumnName =     "anime_id"),
        inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"))
    private final List<Anime> animes = new ArrayList<>();
}

动漫只是持有动漫的数据。 用户拥有用户的用户名等以及他订阅的动画列表。

现在我正在尝试查找一个可以让我获得该列表中所有动画的查询。 它在表中映射为“users_animes”。

因为我对JPQL很新,所以会有很大的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子。我们假设我们有国家实体,可以有多个公民:

@Entity
@Table (name = "countries")
public class Country implements Serializable {

    @Id
    @Column (name = "coun_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column (name = "country_name")
    private String countryName;

    @ManyToMany (cascade = CascadeType.ALL)
    @JoinTable (
            name = "citizen_country",
            joinColumns = @JoinColumn (name = "country_id", referencedColumnName = "coun_id"),
            inverseJoinColumns = @JoinColumn (name = "citizen_id", referencedColumnName = "cit_id")
    )
    private List<Citizen> citizens;

    public Country() {}
    public Country(String countryName) {
        this.countryName = countryName;
    }
    //getters and setters
}

和Citizen,可以属于多个国家:

@Entity
@Table (name = "citizens")
public class Citizen implements Serializable {

    @Id
    @Column (name = "cit_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column (name = "country_name")
    private String citizenName;

    public Citizen() {}

    public Citizen(String citizenName) {
        this.citizenName = citizenName;
    }

    public void setId(Long id) { this.id = id; }
    public Long getId() { return id; }

    public void setCitizenName(String citizenName) { this.citizenName = citizenName; }
    public String getCitizenName() { return citizenName; }

    //getters and setters
}

它是单向的,就像你想要的那样。因此,公民实体不了解国家,因此您无法直接获取某个公民所属的国家/地区的信息。但是,您可以检索有关哪些公民属于某个国家/地区的信息。

更进一步,您可以填充表格:

    Citizen citizen1 = new Citizen("Smith");
    Citizen citizen2 = new Citizen("Kowalski");
    Citizen citizen3 = new Citizen("Muller");
    dataAccess.saveCitizen(citizen1);
    dataAccess.saveCitizen(citizen2);
    dataAccess.saveCitizen(citizen3);

    // now let's fetch them from DB, along with their other properties (only id in this case)
    citizen1 = dataAccess.getCitizenByName("Smith");
    citizen2 = dataAccess.getCitizenByName("Kowalski");
    citizen3 = dataAccess.getCitizenByName("Muller");

    Country country1 = new Country("Foo");
    Country country2 = new Country("Bar");

    // create lists to hold citizens for each country
    List<Citizen> citizenList1 = new ArrayList();
    List<Citizen> citizenList2 = new ArrayList();

    // add elements to the lists
    citizenList1.add(citizen1);
    citizenList1.add(citizen2);        
    citizenList2.add(citizen2);
    citizenList2.add(citizen3);

    //assign lists of citizens to each country
    country1.setCitizens(citizenList1);
    country2.setCitizens(citizenList2);

    //save data in DB
    dataAccess.saveCountry(country1);
    dataAccess.saveCountry(country2);

    //fetch list of all persisted countries (associated Citizens will come along)
    countries = dataAccess.getAllCountries();

最后:

@Stateless
public class DataAccess {

    @PersistenceContext
    EntityManager em;

    public void saveCountry(Country country) {
        em.persist(country);
    }

    public void saveCitizen(Citizen citizen) {
        em.persist(citizen);
    }

    public Citizen getCitizenByName(String name) {
        Query query = em.createQuery("SELECT c FROM Citizen c WHERE c.citizenName = :name");
        query.setParameter("name", name);
        return (Citizen) query.getSingleResult();
    }

    public List<Country> getAllCountries() {
        Query query = em.createQuery("SELECT c FROM Country c");
        return (List<Country>) query.getResultList();
    }


}