简体   繁体   English

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

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

Let me consider one simple sql query 让我考虑一个简单的SQL查询

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

How can i write this query in hibernate using criteria 如何使用条件在休眠模式下编写此查询

Thanks. 谢谢。 Hoping for positive response.. 希望能得到积极的回应。

first you have to create the Criteria object, then you need to pass the where clause condition to the criteria object as well you have to set the projection property for selecting particular column data. 首先,您必须创建Criteria对象,然后需要将where子句条件传递给Criteria对象,还必须设置投影属性以选择特定的列数据。

By seeing your SQL query, 通过查看您的SQL查询,

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

I believe you want to fetch the particular column username from the table tbl_customer . 我相信您想从表tbl_customer获取特定的列username This can be done using Projections . 这可以使用Projections完成。 You have to set the projection property for which column data you want. 您必须设置所需的列数据的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();

This will return only the username column data from that table. 这将仅返回该表中的用户名列数据。

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

Please note that, I do consider entity name as Customer for tbl_customer and you created session correctly. 请注意,我确实将实体名称视为tbl_customer Customer ,并且您正确创建了会话。

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

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