1. 程式人生 > >Spring入門第二十五課

Spring入門第二十五課

struct java 映射 構造器 into named put per mysq

使用具名參數

直接看代碼:

db.properties

jdbc.user=root
jdbc.password=logan123
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/selective-courses-system

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

applicationContext.xml

<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"
> <!-- 導入資源文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置C3P0數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <
property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置Spring的JDBCTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置NamedParameterJdbcTemplate,該對象可以使用具名參數,其沒有無參的構造器,所以必須為其構造器指定參數 --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"></constructor-arg> </bean> </beans>
package logan.study.spring.jdbc;

public class Student {
    String student_id;
    String student_name;
    String card_id;
    String student_class;
    String sex;
    String password;
    String perovince;
    String address;
    String tel;
    String interests;
    public String getStudent_id() {
        return student_id;
    }
    public void setStudent_id(String student_id) {
        this.student_id = student_id;
    }
    public String getStudent_name() {
        return student_name;
    }
    public void setStudent_name(String student_name) {
        this.student_name = student_name;
    }
    public String getCard_id() {
        return card_id;
    }
    public void setCard_id(String card_id) {
        this.card_id = card_id;
    }
    public String getStudent_class() {
        return student_class;
    }
    public void setStudent_class(String student_class) {
        this.student_class = student_class;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPerovince() {
        return perovince;
    }
    public void setPerovince(String perovince) {
        this.perovince = perovince;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getInterests() {
        return interests;
    }
    public void setInterests(String interests) {
        this.interests = interests;
    }
    @Override
    public String toString() {
        return "Student [student_id=" + student_id + ", student_name=" + student_name + ", card_id=" + card_id
                + ", student_class=" + student_class + ", sex=" + sex + ", password=" + password + ", perovince="
                + perovince + ", address=" + address + ", tel=" + tel + ", interests=" + interests + "]";
    }
    
    
    

}
package logan.study.spring.jdbc;

import static org.junit.Assert.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

public class JDBCTest {
    
    private ApplicationContext ctx = null;
    private JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
        namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class);
    }

    @Test
    public void testDataSource() throws SQLException {
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
    /**
     * 使用具名參數可以使用update(String sql, SqlParameterSource paramSource)方法進行更新
     * 1.SQL語句中的參數名和類的屬性名一樣。
     * 2.使用SqlParameterSource的BeanPropertySqlParameterSource實現類作為參數
     */
    @Test
    public void testNamedParameterJdbcTemplate2(){
        String sql = "INSERT INTO student_info (student_id,student_name) VALUES(:student_id,:student_name)";
        Student student = new Student();
        student.setStudent_id("100");
        student.setStudent_name("小周");
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(student);
        namedParameterJdbcTemplate.update(sql, paramSource);
    }
    /**
     * 可以為參數起名字
     * 1.好處:若有多個參數,則不用再去對應位置,直接對應參數名,便於維護
     * 2.缺點:較為麻煩
     */
    @Test
    public void testNamedParameterJdbcTemplate(){
        String sql = "INSERT INTO student_info (student_id,student_name) VALUES(:si,:sn)";
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("si", "HH");
        paramMap.put("sn", "小樓");
        namedParameterJdbcTemplate.update(sql, paramMap);
    }
    /**
     * 獲取單個列的值,或者做統計查詢
     */
    @Test
    public void testQueryForObject2(){
        String sql = "SELECT count(*) FROM student_info";
        long count = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(count);
    }
    
    /**
     * 查到實體類的集合
     */
    @Test
    public void testQueryForList(){
        String sql = "SELECT student_id,student_name,card_id,class student_class,sex,password,perovince,tel,interests from student_info where student_id > ?";
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
        List<Student> students = jdbcTemplate.query(sql, rowMapper,5);
        System.out.println(students);
    }
    /**
     * 從數據庫中獲取一條記錄,實際得到對應的一個對象
     * 註意不是調用queryForObject(String sql,Class<Student> requiredType,Object... args)方法!
     * 而是調用queryForObject(String sql,RowMapper<Student> rowMapper,Object... args)方法!
     * 1.其中的RowMapper指定如何去映射結果集的行,常用的實現類為BeanPropertyRowMapper
     * 2.使用SQL中列的別名完成列名和類的屬性名的映射。例如class student_class
     * 3.不支持級聯框架,JdbcTemplate到底是一個JDBC的小工具,而不是ORM框架。
     */
    @Test
    public void testQueryForObject(){
        String sql = "SELECT student_id,student_name,card_id,class student_class,sex,password,perovince,tel,interests from student_info where student_id=?";
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
        Student student = jdbcTemplate.queryForObject(sql, rowMapper,1);
        System.out.println(student);
    }
    /**
     * 執行批量更新,批量INSERT,UPDATE,DELETE
     * 
     */
    @Test
    public void testBatchUpdate(){
        String sql = "INSERT INTO student_info (student_id,student_name) VALUES(?,?)";
        List<Object[]> pss = new ArrayList<Object[]>();
        pss.add(new Object[]{"009","AA"});
        pss.add(new Object[]{"010","BB"});
        pss.add(new Object[]{"011","CC"});
        pss.add(new Object[]{"012","DD"});
        pss.add(new Object[]{"013","EE"});
        pss.add(new Object[]{"014","FF"});
        pss.add(new Object[]{"015","GG"});
        jdbcTemplate.batchUpdate(sql, pss);
        
        
    }
    /**
     * 執行INSERT,UPDATE,DELETE
     */
    @Test
    public void testUpdate(){
        String sql = "UPDATE student_info SET student_name = ? WHERE student_id = ?";
        jdbcTemplate.update(sql,"小黑","002");
    }

}

Spring入門第二十五課