我在数据库USER_DETAILS和Address中有两个表。这两个表的实体类都在
之下@Entity
@Table(name="USER_DETAILS")
public class UserDetails {`
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int UserID;
private String UserName;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Address> address=new ArrayList<>();
-------------------------------------------------------------
@Entity
public class Address {
@Id @Column(name="ADD_ID") @GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
private String street;
private String city;
我想执行一个查询,以便它返回UserName =“user1”和的所有结果 address.city = 'City1' 当我执行sql查询
时SELECT u.UserName,a.street
from USER_DETAILS u, Address a
where u.UserName='user1'
and a.city='City1';
结果是
+----------+---------+
| UserName | street |
+----------+---------+
| user1 | street1 |
+----------+---------+
但是当我为上面的标准查询运行时
Criteria criteria=session.createCriteria(UserDetails.class,"user")
.createAlias("address", "ad")
.add(Restrictions.eq("user.UserName", "user1"))
.add(Restrictions.eq("ad.street", "street2"));
它显示的结果与预期完全不同,
user1
City2 :: street2
City6 :: street6
City4 :: street4
City8 :: street8
City0 :: street0
我尝试了其他选项,例如createQuery("Address")
而不是createAlias()
。但结果相同。请提出你的建议。
谢谢
编辑:我使用的HQl查询类似于我用作sql的
List<Object[]> list=session.createQuery("select u.UserName,a.street "
+" from UserDetails u,Address a"
+ " where u.UserName=:username and a.city=:cityname")
.setString("username", "user1")
.setString("cityname", "City1")
.list();
我得到了与sql相同的结果,这是正确的结果。但标准没有显示正确的结果。
答案 0 :(得分:0)
如下所示
<强> HQL / SQL 强>
SELECT u.UserName,a.street
from USER_DETAILS u
inner join u.Address ua
where u.UserName='user1'
and ua.city='City1';
标准API
Criteria c = session.createCriteria(UserDetails.class, "u");
c.createAlias("user.Address", "ua");
c.add(Restrictions.eq("u.UserName", "user1")
c.add(Restrictions.eq("ua.city", "City1");
请点击此处了解更多info。