繁体   English   中英

如何使用条件在休眠模式下编写“ where”查询

[英]How to write a 'where' query in hibernate using criteria

让我考虑一个简单的SQL查询

select username from tbl_customer where username="user" and password="12345";

如何使用条件在休眠模式下编写此查询

谢谢。 希望能得到积极的回应。

首先,您必须创建Criteria对象,然后需要将where子句条件传递给Criteria对象,还必须设置投影属性以选择特定的列数据。

通过查看您的SQL查询,

select username from tbl_customer where username="user" and password="12345";

我相信您想从表tbl_customer获取特定的列username 这可以使用Projections完成。 您必须设置所需的列数据的projection属性。

Criteria criteria = session.createCriteria(MyClass.class)
  criteria.setProjection(Projections.property("username"));
  criteria.add(Restrictions.and(Restrictions.eq("username", user),Restrictions.eq("password", 12345))
);
List<String> userNames = criteria.list();

这将仅返回该表中的用户名列数据。

Criteria criteria = session.createCriteria(Customer.class) 
.add(Restrictions.eq("username", 
"user").add(Restrictions.eq("password","12345")); 

请注意,我确实将实体名称视为tbl_customer Customer ,并且您正确创建了会话。

暂无
暂无

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

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