我有一个User
类,它具有@OneToMany
List<Address>
属性。 Hibernate已经在用户和地址之间创建了一个连接表。当用户登录时,我使用自定义SQL查询查找用户;休眠定制查找器SQL查询不返回OneToMany关系
select * from user where username = ? and password = ?
这显然将返回用户的所有其他领域,但不是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;
}
@SotiriosDelimanolis你提到'我有,有一个@OneToMany列表
'用户类,对吧? 'List '的字段名称是什么?我只是用它作为地址。需要相应地更改查询。 –@SotiriosDelimanolis然后您需要使用@ JoinTable注释来更新您的用户实体类,并使用Yogendra中描述的hql。请看这个例子,我无法测试功能,但应该给你一个想法,并在谷歌更多的资源:http://tadtech.blogspot.cz/2007/09/hibernate-annotation-one-to-many-join。 html – HRgiger
@SotiriosDelimanolis这很好。我更新了答案。尝试使用更新后的查询。它应该与用户一起加载地址。 –