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 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执行的持久化操作。(上面的函数,是用hirbernate的回调函数来删除id,因为类型是int,所以最后return的时候需要转换一下类型。)
同理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); }
(此处的c为别名)
原标题:sql,hql的写法
关键词:sql