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的降序排列,自然第一条就是当前数据邻近的上一条,同理可得下一条!!
本文通过使用Hibernate实现MySQL分页SQL语法,提供了一种获取特定记录上下相邻记录的方法,详细介绍了上一条记录和下一条记录的获取过程。
1172

被折叠的 条评论
为什么被折叠?



