Hibernate获取'上一条'和'下一条'记录
暂且把废话放一边,代码上:
/** |
* 上一条记录 |
* @param id |
* @return |
*/ |
@Override |
public Object preBlog(String id) { |
final String fid = id; |
final String sql = "from Blog b where b.bid<? order by b.bid desc" ; |
return this .getHibernateTemplate().execute( new HibernateCallback() { |
@Override |
public Object doInHibernate(Session session) |
throws HibernateException, SQLException { |
Object obj = session.createQuery(sql).setString( 0 , fid).setMaxResults( 1 ).uniqueResult(); |
System.out.println(((Blog)obj).getBid()); |
return obj; |
} |
}); |
} |
/** |
* 下一条记录 |
* @param id |
* @return |
*/ |
@Override |
public Object nextBlog(String id) { |
final String fid = id; |
final String sql = "from Blog b where b.bid>? order by b.bid asc" ; |
return this .getHibernateTemplate().execute( new HibernateCallback() { |
@Override |
public Object doInHibernate(Session session) |
throws HibernateException, SQLException { |
Object obj = session.createQuery(sql).setString( 0 , fid).setMaxResults( 1 ).uniqueResult(); |
System.out.println(((Blog)obj).getBid()); |
return obj; |
} |
}); |
} |
其实我这种思想是利用了mysql分页的sql语法,小于当前id的数据的所有的i的降序排列,自然第一条就是当前数据邻近的上一条,同理可得下一条!!