Hibernate操作数据库的回调机制--Callback
Hibernate操作数据库的回调机制--Callback
1:一般情况下,在使用Hibernate Session存取数据库的代码中,基本上大部分是相同的,如下两个方法所示,
- //查询Teacher操作
- ublic Teacher getTeacher(Long id) throws DataAccessException {
- Session session = getSession();
- Teacher teacher = null;
- try {
- teacher = (Teacher)session.get(Teacher.class, id);
- ...
- } catch(HibernateException ex) {
- throw convertHibernateAccessException(ex);
- } catch(SQLException ex) {
- throw convertJdbcAccessException(ex);
- } catch(RuntimeException ex) {
- throw ex;
- } finally {
- session.close();
- return teacher;
- }
- //查询Class操作
- ublic classInfo getTeacher(Long id) throws DataAccessException {
- Session session = getSession();
- ClassInfo classInfo = null;
- try {
- classInfo = (ClassInfo)session.get(ClassInfo.class, id);
- ...
- } catch(HibernateException ex) {
- throw convertHibernateAccessException(ex);
- } catch(SQLException ex) {
- throw convertJdbcAccessException(ex);
- } catch(RuntimeException ex) {
- throw ex;
- } finally {
- session.close();
- return classInfo;
- }
和异常处理部分进行封装,形成一个公共的方法,如下面代码所示,
- //封装后公用方法
- ublic Object process(HibernateCallback action) throws DataAccessException {
- Session session = getSession();
- Object obj = null;
- try {
- obj = action.doInHibernate(session);
- } catch(HibernateException ex) {
- throw convertHibernateAccessException(ex);
- } catch(SQLException ex) {
- throw convertJdbcAccessException(ex);
- } catch(RuntimeException ex) {
- throw ex;
- }
- //查询Teacher操作
- public Teacher getTeacher(final Long id) throws DataAccessException {
- return (Teacher)process(new HibernateCallback(){
- public Object doInHibernate(Session session) throws HibernateException, SQLException {
- Teacher teacher = (Teacher)session.get(Teacher.class, id);
- return teacher;
- }
- });
- }
而不用处理一些底层通用操作,从而可以实现通用操作和业务逻辑相分离。比如在Java数据库操作中,使用回调机制,不用关心数据库连接的打开和关闭,只需要在Callback实现相关的数据存取即可,这样可以从一定程度上保证数据库连接总是被及时关闭。
评论暂时关闭