I am developing an application using Spring rest and Hibernate and I want to get nested records from database like I'm getting Profession
for a User
, now I want to fetch Users
associated to the Profession
I fetched previously.
Here is my Dao class
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Profession> getProfessionById(long id) throws Exception {
session = sessionFactory.openSession();
Criteria cr = session.createCriteria(Profession.class);
cr.add(Restrictions.eq("uid", id));
List results = cr.list();
tx = session.getTransaction();
session.beginTransaction();
tx.commit();
return results;
}
According to you query, the Profession table has a uid
column which is probably a FK to the Users
table and I think the Users
table should have a FK to the Profession instead.
So the Users
table will have a many-to-one
association to a Profession
:
@ManyToOne
private Profession profession;
and the Profession
can associate all Users having that particular profession, so in the Profession
entity you have the inverse side of this association:
@OneToMany(mappedBy = "profession")
private List<Users> users = new ArrayList<>();
Now to get all users having a profession you can run a simple query like this:
List<Users> users = (ist<Users>) session.createQuery(
"select u " +
"from Profession p " +
"join fetch p.users u " +
"where p.id = :id")
.setParameter("id", proffesionId)
.list();
First you need to add below mapping in Profession and User entity class
In Profession class
//bi-directional many-to-one association to Users
@OneToMany(mappedBy="profession", cascade=CascadeType.ALL)
private List<User> users;
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
In User entity class
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="profession_id")
private Profession profession;
Then you can fetch profession object by id using your existing DAO class code.
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Profession> getProfessionById(long id) throws Exception {
session = sessionFactory.openSession();
Profession profession = (Profession) session.get(Profession.class, id);
// here you can get list of users for this profession
// List<User> users = profession.getUsers();
return profession;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With