1.对象化查询Criteria方法:
static void cri(String name,String password){
Session s=null;
try{
s=HibernateUtil.getSession();
Criteria c=s.createCriteria(Admin.class);
c.add(Restrictions.eq("aname",name));//eq是等于,gt是大于,lt是小于,or是或
c.add(Restrictions.eq("apassword", password));
List<Admin> list=c.list();
for(Admin admin:list){
System.out.println(admin.getAname());
}
}finally{
if(s!=null)
s.close();
}
}
2.动态分离查询DetachedCriteria
static List dc(DetachedCriteria dc) {
Session s = HibernateUtil.getSession();
Criteria c = dc.getExecutableCriteria(s);
List rs = c.list();
s.close();
return rs;
}
DetachedCriteria dc = DetachedCriteria.forClass(User.class);
int id = 1;
if (id != 0)
dc.add(Restrictions.eq("id", id));
Date age = new Date();
if (age != null)
dc.add(Restrictions.le("birthday", age));
List users = dc(dc);
System.out.println("离线查询返回结果:" + users);
3.例子查询
static List example(User user) {
Session s = HibernateUtil.getSession();
List<User> users = s.createCriteria(User.class).add(
Example.create(user)).list();
// List<User>
// users2=s.createCriteria(User.class).add((Example.create(user)).ignoreCase())
// .createCriteria("child").add((Example.create(user))).list();
return users;
}
4.sql查询
static List sql() {
Session s = HibernateUtil.getSession();
Query q = s.createSQLQuery("select * from user").addEntity(User.class);
List<User> rs = q.list();
s.close();
return rs;
}
5.命名查询
static List namedQuery(int id) {
Session s = HibernateUtil.getSession();
Query q = s.getNamedQuery("getUserById");
q.setInteger("id", id);
return q.list();
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sy.vo.User" table="user" catalog="news">
</class>
<!-- 命名查询:定义查询条件 -->
<query name="getUserById">
<![CDATA[from User where id=:id]]>
</query>
<!-- 命名查询中使用sql,不推荐使用,影响跨数据库
<sql-query name="getUserById2">
<![CDATA[select * from User where ]]>
</sql-query> -->
</hibernate-mapping>
6.HQL查询
看上文.......