sql,hql的写法

 1 public List getList(long id){
 2         String sql="select 字段 from 对象"+" where p.id="+id;
 3         Session sess=null;
 4         try{
 5             sess=this.getSession();
 6             SQLQuery q = sess.createSQLQuery(sql);
 7             return q.list();
 8         }finally{
 9             if(sess!=null){
10                 this.releaseSession(sess);
11             }
12         }
13     }
public List getList(long id){
            String sql="select 字段 from 对象+ " where p.id="+id; 
        return this.getHibernateTemplate().find(sql); }
public int delete(final long id) {
            Object obj = this.getHibernateTemplate().execute(
                         new HibernateCallback() {
                               public Object doInHibernate(Session session)
                                           throws HibernateException, SQLException {
                  String hql = "delete 对象 where id=:id";
                  return new Integer(session.createQuery(hql).setLong( "id", id).executeUpdate());
                              }
                        });
             return ((Integer) obj).intValue();
      }
HibernateCallback是回调函数,是一个接口,该接口只有一个方法doInHibernate(org.hibernate.Session session),
这个方法体就是Spring执行的持久化操作。这里用到了(:id)这种别名的方式设置参数。(上面的函数,是用hirbernate的回调函数来删除id,因为类型是int,所以最后return的时候需要转换一下类型。)
   我们也可以用?的参数化方式:
/**
             * 查询中使用?,通过setParameter的方式可以防止sql注入
             * jdbc的setParameter的下标从1开始,hql的下标从0开始
             */
            List<Student> students = (List<Student>)session.createQuery("select xxx from 表 where aa like ?") .setParameter(0, "%王%") .list();
1)同理update:
public int update(final long fId,final long cId) {
        Object obj=this.getHibernateTemplate().execute(
                new HibernateCallback(){
                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        String hql = "update 对象 set"+
                            " bId="+cId+
                            " where bId="+fId;
                        Query q=session.createQuery(hql);
                        return new Integer(q.executeUpdate());
                    }
                }
            );
        return ((Integer)obj).intValue();
    }        
public List<?> getList(boolean justEnabled){
            String sql="from 对象 c";
            if(justEnabled){
                sql=sql+" where c.enabled='Y'";
            }
            return this.getHibernateTemplate().find(sql);
        }

2)同样update,可以用set方式传数据。

public int updateTwo(final long id, final String a, final BigDecimal b) {
            Object obj = this.getHibernateTemplate().execute(
                         new HibernateCallback() {
                               public Object doInHibernate(Session session) throws HibernateException, SQLException {
                                    String hql = "update C set a=:a,b=:b,where id = " +id;
                                     return new Integer(session.createQuery(hql)
                                          .setString( "a", a)
                                          .setBigDecimal( "b", b)
                                          .executeUpdate());
                              }
                        });
             return ((Integer) obj).intValue();
      }

(此处的c为别名)

========

补充一个方法findByNamedParam,这个方法根据参数类型,可以有多个写法。

1.

 public User get(String str) {
        String sql= "from User  u" +
            " where u.boss = :str" +
            " and u.enabled='Y'"+
            " order by u.id";
        String[] paramNames= new String[]{"str" };
        Object[] values= new Object[]{str};
        List<?> list = this.getHibernateTemplate().findByNamedParam(sql,paramNames,values);
        if(list.isEmpty()){
            return null ;
        } else{
            return (User)list.get(0);
        }
    }

2.

String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";

String[] paramName= new String[]{"myName" "myPassword"};

String[] value= new String[]{"admin" "123"};

this.getHibernateTemplate().findByNamedParam(queryString paramName value);

返回用户名为admin密码为123的User对象

3.

String queryString = "select count(*) from bean.User u where u.name=:myName";

String paramName= "myName";

String value= "admin";

this.getHibernateTemplate().findByNamedParam(queryString paramName value);

System.out.println(list.get(0));

返回name为admin的User对象的条数

 补充:

4.用in进行列表查询:

 List<Student> stus = (List<Student>)session.createQuery("select stu from Student stu where stu.room.id in (:room) and stu.sex like :sex")
                                                .setParameterList("room", new Integer[]{1, 2}).setParameter("sex", "%女%")
                                                .list();

5.分页查询:

/**
             * 通过setFirstResult(0).setMaxResults(10)可以设置分页查询,相当于offset和pagesize
             */
            List<Student> stus = (List<Student>)session.createQuery("select stu from Student stu where stu.room.name like :room and sex like :sex")
                                                .setParameter("room", "%计算机应用%").setParameter("sex", "%女%").setFirstResult(0).setMaxResults(10)
                                                .list();
原文地址:https://www.cnblogs.com/charles-kun/p/5466151.html