2

我有一个User@OneToMany List<Address>属性的类。Hibernate 在用户和地址之间创建了一个连接表。当用户登录时,我使用自定义 SQL 查询查找用户;

select * from user where username = ? and password = ?

这显然会返回 user 的所有其他字段,但不返回List<Address>. Hibernate 有没有办法在不使用自定义查询的情况下也返回关系数据?

我可以通过上面的自定义查询加载用户,提取其 ID,然后重新加载用户以便 Hibernate 加载所有字段吗?有没有更好的方法?

@Entity
public class User {

    @Id
    @GeneratedValue
    @GenericGenerator(name = "incremental", strategy = "increment")
    private Long userID;

    @Column(nullable = false)
    private String username;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_address", 
        joinColumns = @JoinColumn(name = "userID"), 
        inverseJoinColumns = @JoinColumn(name = "addressID"))
    private List<Address> addresses;
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NonVisual
    public Long addressID;
}
4

2 回答 2

2

尝试使用 HQL,如下所示:

String queryString = "select u from User u left join u.addresses "+
                     "where u.username = :userName and u.password = :password";

编辑:执行 HQL 的示例代码

String queryString = "select u from User u left join u.addresses "+
                     "where u.username = :userName and u.password = :password";
Query query = session.createQuery(queryString );
query.setParameter("userName", userNameValue);
query.setParameter("password", passwordValue);
List<User> users = query.list();
于 2012-11-27T19:50:56.633 回答
0

默认情况下,您有惰性属性关联,您需要调用getAddresses()用户来检索惰性集合。

集合需要更多的工作来初始化——你当然可以通过遍历整个集合来手动完成,但最好调用 Hibernate 实用程序类来为你做这件事。该Hibernate.initialize方法将对象作为参数,并初始化任何惰性关联(包括集合)。所以,如果你想完全初始化用户,然后完全初始化地址集合:

Object[] userObject; // the object returned by the query.
User u = new User(userObject); // create the user
Hibernate.initialize(u); // initializes user
Hibernate.initialize(u.getAddresses()); // pass the lazy collection into the session to be initialized.
于 2012-11-27T20:26:48.237 回答