Search code examples
javasqlhibernatemany-to-many

Retrieve data from many to many table in hibernate


I have a many to many relationship between users and adverts which is mapped like this

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "faved_ads",
           joinColumns = {@JoinColumn(name = "advert_id", nullable = false, updatable = false)},
           inverseJoinColumns = {@JoinColumn(name = "user_id", nullable = false, updatable = false)})
public List<User> getFavouriters() {
    return favouriters;
}


    @ManyToMany(mappedBy = "favouriters")
public List<Advert> getFavourites() {
    return favourites;
}

How do I retrieve this data back from the database if I was wanting to find all the ads a certain user had favourited? Can it be done through creating criteria restrictions or projections?

This is how i've retrieved data from a one to many but can't get a similar solution for many to many

    public static <T> List<T> getList(Criteria criteria) {
    List<T> results = null;
    try {
        transaction = session.beginTransaction();
        results = criteria.list();
        transaction.commit();
    } catch (HibernateException ex) {
        transaction.rollback();
        ex.printStackTrace();
    } finally {
        session.close();
    }
    return results;
}

    public static List<Advert> usersAdverts(User user) {
    session = HibernateUtil.getSessionFactory().openSession();
    Criteria cr = session.createCriteria(Advert.class);
    cr.createAlias("user", "user");
    cr.add(Restrictions.eq("user.id", user.getId()));
    return getList(cr);
}

Thanks


Solution

  • I guess that you don't need any criteria to find all the ads a certain user had favourited. It is simply:

    public static List<Advert> usersAdverts(User user) {
        Hibernate.initialize(user.getFavourites());
        return user.getFavourites(); 
    }
    

    However, if the user object is detached from the session - then open a new transaction, re-read the object and initialize its collection as I offered above (before detaching user from the session!).

    :-)