Reputation: 658
I have a class User
, that contains List of Contacts
User class:
@Entity
@Table(name = "profile")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(unique = true)
private String login;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
private List<Contact> contacts;
...
...
}
Contact class:
@Entity
@Table
public class Contact implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "user_profile_id")
private User owner;
...
...
}
how may i get List of Contacts by User.id field?
Upvotes: 0
Views: 4390
Reputation: 19956
Contact
has a foreign key column associated to User
so you don't need to use join
from Contact where owner.id = :userId
Please, don't use primitive types like int id
, use Integer id
instead.
Upvotes: 0
Reputation: 494
Not sure I got what you want...
Simply look for the User by Id, and you will get his/her contacts. However, the collection will be lazy loaded, and the list will be really loaded when you will call getContacts()
or Hibernate.initialize(user.getContacts())
. Change FetchMode as EAGER in the @OneToMany in case you don't want lazy loading...
For e.g., using HQL Query :
String hql = "from User where id = :userid";
Query query = session.createQuery(hql);
query.setInteger("userid", myUserIdIWantContacts);
User user = (User) query.uniqueResult();
or Criteria :
Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq("id", myUserIdIWantContacts));
User user = (User) cr.uniqueResult();
Upvotes: 1