• (七)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() + "	"
                        + "userid=" + user.getUserid() + "	" + "isadmin?"
                        + user.getIsAdmin());
    
                tran.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tran.rollback();
            } finally {
                HibernateUtil.closeSession();
            }
    
        }
    
    }

    结果:

    代码在下面章节

  • 相关阅读:
    java_doc
    zai~~myGODDDD
    get span time
    someThing about thread
    互斥
    http://www.vchelp.net/services/about_us/itbookreview_intro.asp
    (十三)sealed、new、virtual、abstract 和 override java程序员
    (15) 常用基础知识 java程序员
    (14)abstract class 和 interface java程序员
    (16) 结构和类 java程序员
  • 原文地址:https://www.cnblogs.com/shyroke/p/6849293.html
Copyright © 2020-2023  润新知