(七)Hibernate中使用JDBC

  • 在hibernate中获取connection数据库连接有两种方法:(操作数据库常用这种方法)
  •  1. session.doReturningWork   返回一个对象,适用于查询方法
  •  2. session.doWork      不返回对象,适用于增删改

案例一:

package action;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.jdbc.ReturningWork;

import bean.User;
import util.HibernateUtil;

public class Query_JDBC {
    public static void main(String[] args) {
        Query_JDBC.jdbc();
    }

    /**
     * 在Hibernate中获取Connection接口
     */
    private static void jdbc() {

        Session session = null;
        Transaction tran = null;

        try {

            session = HibernateUtil.getSession();
            tran = session.beginTransaction();

            User user = session.doReturningWork(new ReturningWork<User>() {

                @Override
                public User execute(Connection conn) throws SQLException {
                    QueryRunner queryRunner = new QueryRunner();
                    String sql = "select username,userid,is_admin as isadmin from user where userid=1";   //数据库中的is_admin和bean中的isdmin不一致
                    User user = queryRunner.query(conn, sql,
                            new BeanHandler<User>(User.class));

                    return user;
                }

            });

            System.out.println("username=" + user.getUsername() + "\t"
                    + "userid=" + user.getUserid() + "\t" + "isadmin?"
                    + user.getIsAdmin());

            tran.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tran.rollback();
        } finally {
            HibernateUtil.closeSession();
        }

    }

}

结果:

 

代码在下面章节

 

posted @ 2017-05-13 16:32  shyroke、  阅读(592)  评论(0编辑  收藏  举报
作者:shyroke 博客地址:http://www.cnblogs.com/shyroke/ 转载注明来源~