HQL查询入门

Query q = session.createQuery(hql);
1.from Person
2.from User user where user.name=:name
3.from User user where user.name=:name and user.birthday < :birthday

Query
1.根据name查询全部
public void query(String name){
 Session session = null;
 try{
   session = HibernateUtil.getSession();
   String hql = "from User as user where user.name=?";
   Query query = session.createQuery(hql);
   query.setString(0,name);
   List<User> list = query.list();//executQuery()
   for(User user:list){
    System.out.println(user.getName());
   } 
  }finally{
   if(session != null){
    session.close();
   }
  } 
}
2.查询一个对象(uniqueResult_如果有几条记录会报异常)
public void query(String name){
 Session session = null;
 try{
   session = HibernateUtil.getSession();
   String hql = "from User as user where user.name=?";
   Query query = session.createQuery(hql);
   query.setString(0,name);
   List<User> list = query.list();//查询所有
   User user = query.uniqueResult();//当确定只有一条记录
   for(User user:list){
    System.out.println(user.getName());
   } 
  }finally{
   if(session != null){
    session.close();
   }
  } 
}

当实当实体类跟数据库关键字有冲突时:`user`反引号或table="user"


hibernate.properties

用命名参数代替?
String hql="from User as user where user.name=:n";
query query = session.createQuery(hql);
query.setString("n",name);

实现分页语句(跨数据库根据方言dialet自己判断使用哪种数据库的分页)
query.setFirstResult(0);从哪开始
query.setMaxResult(10);取多少条


Criteria查询方式:

Criteria ctiteria = session.createCriteria(User.class);
ctiteria.add(Restrictions.eq("name",zchen));//eq等于 name属性等于zchen

你可能感兴趣的:(Hibernate)