spring jdbcTemplate

  jdbcTemplate是Spring針對JDBC代碼失控提供的解決方案,嚴格來講,它自己也不算成功。可是不管如何jdbcTemplate的方案也體現了Spring框架的主導思想之一:給予經常使用技術提供模板化的編程
  對jdbcTemplate進行配置java

<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 數據庫鏈接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>      <!--鏈接池的最大數據庫鏈接數-->
        <property name="maxActive" value="255"/>      <!--最大等待鏈接中的數量-->
        <property name="maxIdle" value="5"/>      <!--最大等待毫秒數-->
        <property name="maxWait" value="10000"/>
    </bean>

</beans> 

  

  代碼清單:經過jdbcTemplate操做數據庫mysql

ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter12/spring-cfg.xml");
JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
Long id = 1L;
String sql = "select id, role_name, note from t_role where id = " + id;

Role role = jdbcTemplate.queryForObject(sql, new RowMapper<Role>() {
    @Override
    public Role mapRow(ResultSet rs, int rownum) throws SQLException {
        Role result = new Role();
        result.setId(rs.getLong("id"));
        result.setRoleName(rs.getString("role_name"));
        result.setNote(rs.getString("note"));
        return result;
    }
});
System.out.println(role.toString());

 


  queryForObject方法。它包含兩個參數,一個是SQL,另外一個是RowMapper接口,這裏筆者使用了匿名類,因此採用了new關鍵字去建立一個RowMapper接口對象。若是開發環境是Java 8的,也能夠使用Lambda表達式的寫法
  代碼清單:使用Lambda表達式spring

Role role2 = jdbcTemplate.queryForObject(sql, (ResultSet rs, int rownum) -> {
    Role result = new Role();
    result.setId(rs.getLong("id"));
    result.setRoleName(rs.getString("role_name"));
    result.setNote(rs.getString("note"));
    return result;
});
System.out.println(role2.toString());

 

  這樣就更爲清晰一些,不過它們都是大同小異的寫法,在mapRow方法中,從ResultSet對象中取出查詢獲得的數據,組裝成一個Role對象,而無須再寫任何關閉數據庫資源的代碼。由於jdbcTemplate內部實現了它們,這即是Spring所提供的模板規則。sql

jdbcTemplate的增、刪、查、改

  代碼清單:jdbcTemplate的增、刪、查、改數據庫

package com.ssm.chapter12.jdbc;

import com.ssm.chapter11.game.pojo.Role;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class MainTest {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter12/spring-cfg.xml");
        JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);

        insertRole(jdbcTemplate);
        List roleList = findRole(jdbcTemplate, "role");
        System.out.println(roleList.toString());
        Role role3 = new Role();
        role3.setId(5L);
        role3.setRoleName("update_role_name_5");
        role3.setNote("update_note_5");
        int i = updateRole(jdbcTemplate, role3);
        System.out.println("update:" + i);
        int i1 = deleteRole(jdbcTemplate, 5L);
        System.out.println("delete:" + i1);


    }


    /***  * 插入角色  * @param jdbcTemplate --模板  * @return 影響條數  */
    public static int insertRole(JdbcTemplate jdbcTemplate) {
        String roleName = "role_name_1";
        String note = "note_1";
        String sql = "insert into t_role(role_name, note) values(?, ?)";
        return jdbcTemplate.update(sql, roleName, note);
    }

    /**
     * 刪除角色  * @param jdbcTemplate  模板  * @param id  角色編號,主鍵  * @return 影響條數
     */
    public static int deleteRole(JdbcTemplate jdbcTemplate, Long id) {
        String sql = "delete from t_role where id=?";
        return jdbcTemplate.update(sql, id);
    }

    public static int updateRole(JdbcTemplate jdbcTemplate, Role role) {
        String sql = "update t_role set role_name=?, note = ? where id = ?";
        return jdbcTemplate.update(sql, role.getRoleName(), role.getNote(), role.getId());
    }

    /**
     * 查詢角色列表  * @param jdbcTemplate  模板  * @param roleName  角色名稱  * @return 角色列表
     */
    public static List<Role> findRole(JdbcTemplate jdbcTemplate, String roleName) {
        String sql = "select id, role_name, note from t_role where role_name like concat('%',?, '%')";
        Object[] params = {roleName};//組織參數
        // 使用RowMapper接口組織返回(使用lambda表達式)
        List<Role> list = jdbcTemplate.query(sql, params, (ResultSet rs, int rowNum) -> {
            Role result = new Role();
            result.setId(rs.getLong("id"));
            result.setRoleName(rs.getString("role_name"));
            result.setNote(rs.getString("note"));
            return result;
        });
        return list;
    }

}
相關文章
相關標籤/搜索