JPQL manyToMany unidirectional query

572 views Asked by At

I have been looking the forums and everywhere for a unidirectional manyToMany query. I find many examples but i can't really adjust them to my needs :(

I have 2 entity classes (Anime & User)

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

Anime simply holds the data from the anime. User holds the username etc of the user and a list of anime that he subscribed to.

Now i'm trying to find a query that will let me get all the animes in that list. It's mapped in a table as "users_animes".

Would be a huge help since i'm fairly new to JPQL.

Thanks!

1

There are 1 answers

2
mmalik On

Here's a simple example. Let's assume that we have Country Entity, which can have multiple Citizens:

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

And Citizen, which can belong to multiple Countries:

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

It's unidirectional, just as you wanted it to be. Therefore, Citizen Entity is unaware of Country, so you can't get directly information to which Country a certain Citizen belongs. However, you can retrieve info about which Citizens belong to a certain Country.

Going further, you can populate your tables:

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

And finally:

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


}