Sankar
Sankar

Reputation: 59

select query on db using hibernate when bean classes are linked with one to many annotation:

below are my two classes

@Entity
@Table(name="Users")
public class User {

@Id
@Column(name="users_id")
private String userId;

@Column(name="uname")
private String userName;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="users_id")
private Set<Address> addresses;

getters & setters

}

@Entity
@Table(name="Address")
public class Address {

@Id
@Column(name="address_id")
private String addressId;

@Column(name="City")
private String City;

@ManyToOne
private User user;

setters & getters

}

User and Address are two tables where a single user can have multiple addresses. userID is the common column between those two tables.

Now I want to write a select query to get the details of user from User table and all the addresses related to that user and prepare a list of beans accordingly.

Please Help. Thanks in advance.

Upvotes: 1

Views: 237

Answers (1)

mateuszlo
mateuszlo

Reputation: 1419

I'm assuming you are using hibernate Session and not JPA EntityManager. This query will return User with id "123" with its corresponding Addresses filled in.

Query query = session.createQuery("select user from User user left join fetch user.addresses where user.userId = :userId");
query.setParameter("userId", "123");
User user = (User) query.uniqueResult();

Upvotes: 0

Related Questions