如何使用条件在休眠中编写 '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";

我相信您想从 table tbl_customer 中获取特定列 username。这可以使用 Projections 来完成。您必须为您想要的列数据设置投影 属性。

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();

这将 return 只有来自 table 的用户名列数据。

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

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