Spring學習之路:jdbcTemplate的簡單練習,springjdbctemplate

來源:互聯網
上載者:User

Spring學習之路:jdbcTemplate的簡單練習,springjdbctemplate
一、介紹

  Hibernate是對jdbc的重度封裝,使用者感覺不到sql的操作,全用HSQL;mybatis是對jdbc的中度封裝,依舊要寫一些sql,精髓是在於sql的組裝;jdbcTemplate為輕度組裝,它只是將資料庫的串連和關閉封裝了,但是沒有比mybatis智能(體現在未能將查詢出來的結果自動化佈建到model類中),更別說hibernate了

  本次的練習是從jdbctemplate最初的形式開始,一步步地向真正開發實戰中使用的形式靠近。具體內容如下:

    ️、使用DriverManagerDataSource串連資料庫

    ️、對資料庫的操作(增、刪、改)

    ️、使用spring管理jdbcTemplate,這樣會減少很多的代碼

    ️、使用C3P0資料池管理串連:在實際的工作環境中DriverManagerDataSource是不會去使用的,因為每次查詢都要開啟串連,效率太差;在真實的開發中必須要考慮更換資料庫的情況,所以最好的方式是將資料庫連接資訊獨立出來儲存在一個屬性檔案中。

    ️、加入jdbcDAOSupport支援:雖然可以直接利用jdbcTemplate進行資料庫的操作,但在大部分的dao實現中,很少有這樣的人去做,往往讓DAO子類既實現了DAO介面,又同時去繼承一個jdbcTemplate的抽象類別。自動注入過程應該交給一個統一的類來進行處理,所以就定義了一個JdbcDAOSupport類,但是這個類除了負責處理jdbcTemplate類的對象之外,還可以負責資料庫的自動關閉,即如果你想要讓你的開發資料庫可以自動關閉,就必須要繼承jdbcdaosupport類。

二、練習  

  (1)使用DriverManagerDataSource串連資料庫

    public static DriverManagerDataSource getDBManager()throws Exception{        DriverManagerDataSource dbManager=new DriverManagerDataSource();// org.springframework.jdbc.datasource.DriverManagerDataSource
dbManager.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dbManager.setPassword("tiger");
        dbManager.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");        dbManager.setUsername("scott");        Connection conn=dbManager.getConnection();        System.out.println(conn);        return dbManager;    }

  (2)完成資料庫的CRUD操作

    首先瞭解JdbcTemplate這個類:

      • 構造方法:除了無參構造方法之外,還可以直接傳入一個資料來源:public JdbcTemplate(DataSource data);
      • 設定資料來源:public void setDataSource(DataSource data);
      • 普通更新操作:public int update(String sql,Object...args);
      • 更新並取得id:public int update(PreparedStatementCreator psc,KeyHolder generatedKeyHolder) throws DataAccessException;
      • 查詢全部:public <T> List<T> queryForList(String sql,Object[] args,RowMapper<T> rowMapper) throws DataAccessException.
      • 查詢單列:public <T> List<T> queryForList(String sql,Object[] args,Class<T> elementsType) throws DataAccessException.
      • 查詢單個資料:public <T> queryForObject(String sql,Object[] args,Class<T> requiredType) throws DataAccessException.

    下面介紹這些方法的使用:

      1、普通更新操作

    public static boolean update() throws Exception {        JdbcTemplate template=new JdbcTemplate();        template.setDataSource(getDBManager());        String sql="update myemp set job=? where empno=?";        int count=template.update(sql,"CXY",7369);        return count>0;    }

      2、更新並取得id

    //更新,並取得id,id在建表時應該是自增長類型    public static void updateAndGetID() throws Exception{        JdbcTemplate template=new JdbcTemplate();        template.setDataSource(getDBManager());        final String sql="update emp set job=? where empno=?";        KeyHolder key=new GeneratedKeyHolder();        int count=template.update(new PreparedStatementCreator() {            @Override            public PreparedStatement createPreparedStatement(Connection conn)                    throws SQLException {                PreparedStatement pstmt=conn.prepareStatement(sql);                pstmt.setString(1, "CKW");                pstmt.setInt(2, 7369);                return pstmt;            }        },key);        System.out.println("當前的id是:"+key.getKey());        if(count>0)System.out.println("執行成功!");        else System.out.println("執行不成功!");    }

      3、查詢全部,設定到vo時要手動設定,這點比較麻煩,可以使用反射自動化佈建。

    //查詢全部操作,將資料庫中的所有資料查詢出來    public static void getAll() throws Exception{        JdbcTemplate template=new JdbcTemplate();        template.setDataSource(getDBManager());        String sql="select empno,ename,job,mgr,hiredate,sal,comm,deptno from myemp where rownum<=?";        List<Emp> list=template.query(sql,new RowMapper<Emp>(){            @Override            public Emp mapRow(ResultSet rs, int rowCount) throws SQLException {                System.out.println("返回的當前資料行:"+rowCount);                Emp emp=new Emp();                emp.setEmpno(rs.getInt("empno"));                emp.setEname(rs.getString("ename"));                emp.setComm(rs.getInt("comm"));                emp.setDeptno(rs.getInt("deptno"));                emp.setHiredate(rs.getDate("hiredate"));                emp.setJob(rs.getString("job"));                return emp;            }        },10);        System.out.println(list);    }

      4、查詢單列 

    //查詢單列資料    public static void demo5() throws Exception{        JdbcTemplate template=new JdbcTemplate();        template.setDataSource(getDBManager());        String sql="select empno from myemp where rownum<=?";        List<Integer> list=template.queryForList(sql, new Object[]{5}, Integer.class);        System.out.println(list);    }

      5、查詢單個資料

    //查詢單個資料    public static void demo6() throws Exception{        JdbcTemplate temp=new JdbcTemplate();        temp.setDataSource(demo1());        String sql="select count(*) from myemp where rownum<=?";        int i=temp.queryForObject(sql, new Object[]{8}, Integer.class);        System.out.println(i);    }

   

  (3)使用Spring來管理JdbcTemplate

     類比業務層實現入下所示,使用xml中配置的bean進行注入:

@Componentpublic class DAOImpl implements IDAO {    private JdbcTemplate jt;    @Autowired      public DAOImpl(JdbcTemplate jt){        this.jt=jt;    }        @Override    public boolean doCreate(Emp emp) {        String sql="update myemp set job=? where empno=?";        int count=jt.update(sql,emp.getJob(),emp.getEmpno());        return count>0;    }}

 

    在xml中要配置DriverManagerDataSource的bean和JdbcTemplate的bean

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>        <property name="username" value="scott"/>        <property name="password" value="tiger"/>    </bean>    <bean id="jdbcTamplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"/>    </bean> 

 

  (4)使用c3p0來管理jdbc的串連

    首先建立database.properties

db.driver=oracle.jdbc.driver.OracleDriverdb.url=jdbc:oracle:thin:@172.16.237.129:1521:orcldb.user=scottdb.password=tigerpool.max=10pool.min=10pool.init=5pool.idle=5

    在xml中替換練習(3)的配置:

    <context:property-placeholder location="classpath:database.properties"/><!--讀取屬性檔案,路徑是在classpath,練習中為src下可以讀取到-->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="${db.driver}"/>        <property name="jdbcUrl" value="${db.url}"/>        <property name="user" value="${db.user}"/>        <property name="password" value="${db.password}"/>        <!-- 最大可用串連數 -->        <property name="maxPoolSize" value="${db.max}"/>        <!-- 最小維持串連數 -->        <property name="minPoolSize" value="${db.min}"/>        <!-- 初始化串連數 -->        <property name="initialPoolSize" value="${db.init}"/>        <!-- 最大等待串連 -->        <property name="maxIdleTime" value="${db.password}"/>    </bean>      <bean id="jdbcTamplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"/>    </bean> 

  (5)JdbcDaoSupport的支援

    將DAOImpl改寫成如下代碼,紅色部分顯示了與之前的不同之處:

@Componentpublic class DAOImpl extends JdbcDaoSupport implements IDAO {        @Autowired    public DAOImpl(JdbcTemplate jt){        super.setJdbcTemplate(jt);    }        @Override    public boolean doCreate(Emp emp) {        String sql="update myemp set job=? where empno=?";        int count=super.getJdbcTemplate().update(sql,emp.getJob(),emp.getEmpno());        return count>0;    }}

 

 

 

 

小結與問題:

  雖然JdbcTemplate的手動書寫練習(2)代碼比較多,但是在項目中測試的時候可以派上用場,不用修改xml中的內容使得混亂。

  練習(2)中的“更新並取得id”這個函數,取得的是怎麼樣的id並沒有很好的概念。

 

轉載請說明出處~ 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.