依赖接口:Criteria
数据模型:
tb_user(userId,userName)
tb_addr(addrId,addrName,userId)
Entity:
class Addr{
private int addrId;
private String addrName;
}
class User{
private int userId;
private String userName;
private Set addrs = new HashSet();
}
备注:省略geters 和 seters
例:
Criteria c = session.createCriteria(User.class);
c.add(Expression.eq("userId", 1));
user = (User)c.uniqueResult(); //有List users = c.list();
执行为:select * from tb_user where userId = 1;
Expression 的静态接口
User 中的属性和具体的值比较:
eq : 等于(=) Expression.eq("userId",1) select * from tb_user where userId=1
gt : 大于(>) Expression.gt("userId",1) select * from tb_user where userId>1
ge : 大于等于(>=) Expression.ge("userId",1) select * from tb_user where userId>=1
lt : 小于(<) Expression.lt("userId",1) select * from tb_user where userId<1
le : 小于等于(<=) Expression.le("userId",1) select * from tb_user where userId<=1
like:模糊查询 Expression.like("userName","n%") select * from tb_user where userName like 'n%'
between : 在之间(between) Expression.between("userId",1,5) select * from tb_user where userId between 1 and 5
and :
or :
select * from user where userId=3 or userId=6
c.add(Expression.or(Expression.eq("userId",3),Expression.eq("userId",6)));
sql :Expression.sql("lower({alias}.name) like lower(?)","Erica%",Hibernate.STRING);
User 中的属性和Addr 中的属性比较:使用前要调用Criteria 的createAlias
eqProperty("aa.addrId","this.userId")
gtProperty("aa.addrId","this.userId")
geProperty("aa.addrId","this.userId")
ltProperty("aa.addrId","this.userId")
leProperty("aa.addrId","this.userId")
Criteria 的其他接口:
c.createAlias("addrs", "aa") :创建addrs 的别名,效果是查询时带上tb_addr的内联
如果不使用别名:效果是查询时使用左连接
分页
//从第100条开始,检索20条数据
c.setFirstResult(100);
c.setMaxResult(20);
排序
//对结果进行排序
c.addOrder(Order.asc("userId"));//userId的升序
c.addOrder(Order.desc("userName")); //userName的降序
Expression 各方法中的属性名参数是指Entity中对应实际库表字段的属性名,而非库表中的实际字段名称
Expression.eq(Filed field,Value value);
filed 为类的属性