简体   繁体   English

当实体映射为多对一时,热获取带有休眠的对象列表

[英]Hot get List of objects with Hibernate, when Entity mapped as Many To One

I have a class User , that contains List of Contacts User class: 我有一个类User ,其中包含Contacts列表User类:

@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? 我如何通过User.id字段获取联系人列表?

Not sure I got what you want... 不知道我得到了你想要的...

Simply look for the User by Id, and you will get his/her contacts. 只需按ID查找“用户”,即可获得他/她的联系人。 However, the collection will be lazy loaded, and the list will be really loaded when you will call getContacts() or Hibernate.initialize(user.getContacts()) . 但是,集合将被延迟加载,并且当您调用getContacts()Hibernate.initialize(user.getContacts())时,列表将真正加载。 Change FetchMode as EAGER in the @OneToMany in case you don't want lazy loading... 如果您不想延迟加载,请将@OneToMany中的FetchMode更改为EAGER ...

For eg, using HQL Query : 例如,使用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();

Contact has a foreign key column associated to User so you don't need to use join Contact具有与User关联的外键列,因此您无需使用连接

from Contact where owner.id = :userId

Please, don't use primitive types like int id , use Integer id instead. 请不要使用诸如int id类的原始类型,而应使用Integer id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM