Spring学习笔记----JdbcTemplet和NamedParameterJdbcTemplate的使用

JdbcTemplet是Spring下一个很好用的jdbc小工具,而且使用起来也是很简单

需求:实现基本的数据库操作

贴上代码:

dataSource.properties

jdbc.user = root
jdbc.password =123456
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql:///spring1

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

applicationContext.xml



    
    
    
    
        
        
        
        
        
        
    
    
    
        
    

Student.java

package cn.limbo.spring.jdbc;

/**
 * Created by Limbo on 16/7/14.
 */
public class Student {
    private int id;
    private String studentName;
    private String email;
    private int deptId;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getDeptId() {
        return deptId;
    }

    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", studentName='" + studentName + '\'' +
                ", email='" + email + '\'' +
                ", deptId=" + deptId +
                '}';
    }
}


Department.java

package cn.limbo.spring.jdbc;

/**
 * Created by Limbo on 16/7/14.
 */
public class Department {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
JDBCTest.java

package cn.limbo.spring.jdbc;

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;

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

/**
 * Created by Limbo on 16/7/14.
 */
public class JDBCTest {
    private static ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    private static JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
    private static NamedParameterJdbcTemplate namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class);
    public void testDataSource() throws SQLException {
        DataSource dataSource = ctx.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
    }


    /**
     * 执行UPDATE,INSERT,DELETE
     */

    public static void testUpdate()
    {
        String sql = "UPDATE student SET student_name = ? WHERE id = ?";
        jdbcTemplate.update(sql,"Kylin",2);
    }
    /**
     * 批量INSERT,UPDATE,DELETE
     * 最后一个参数是Object[]的list类型,因为修改一条记录需要一个object数组,那么多条就需要多个
     */

    public static void BatchUpdate()
    {
        String sql = "INSERT INTO student(id,student_name,email,Dept_No)VALUES(?,?,?,?)";
        List batchArgs = new ArrayList<>();
        batchArgs.add(new Object[]{4,"AA","[email protected]",1});
        batchArgs.add(new Object[]{5,"BB","[email protected]",2});
        batchArgs.add(new Object[]{6,"CC","[email protected]",1});
        batchArgs.add(new Object[]{7,"DD","[email protected]",2});
        batchArgs.add(new Object[]{8,"EE","[email protected]",1});

        jdbcTemplate.batchUpdate(sql,batchArgs);
    }

    /**
     * 从数据库中获取一条记录,实际得到一个对象
     * 注意不是调用这个方法queryForObject(java.lang.String sql,java.lang.Class requiredType,java.lang.Object... args)
     * 需要调用中这个方法: queryForObject(java.lang.String sql,@NotNull org.springframework.jdbc.core.RowMapper rowMapper,java.lang.Object... args)
     * 1.其中的RowMapper指定如何去映射结果集的行,常用的实现类为BeanPropertyRowMapper<>(Student.class);
     * 2.使用SQL中的列的别名完成列名和类的属性名的映射
     * 3.不支持级联属性
     */

    public static void testQueryForObject()
    {
        String sql = "SELECT id,student_name,email,Dept_No FROM student WHERE id = ?";
        RowMapper rowMapper = new BeanPropertyRowMapper<>(Student.class);
        Student student = jdbcTemplate.queryForObject(sql,rowMapper,1);
        System.out.println(student);
    }

    /**
     * 查到实体类的集合
     * 注意不是调用queryForList
     */

    public static void testQueryForList()
    {
        String sql = "SELECT id, student_name,email,Dept_No FROM student WHERE id > ?";
        RowMapper rowMapper = new BeanPropertyRowMapper<>(Student.class);
        List list = jdbcTemplate.query(sql,rowMapper,1);
        System.out.println(list);

    }

    /**
     * 获取单个列的值,或者做统计查询
     */

    public static void testQueryForObject2()
    {
        String sql = "SELECT count(id) FROM student";
        int count = jdbcTemplate.queryForObject(sql,Integer.class);
        System.out.println(count);
    }

    /**
     * 可以为参数取名字,参数多了更加便于维护
     * 1.好处:若有多个参数,则不用再去对应位置,直接对应参数名,便于维护
     * 2.缺点:较为麻烦
     */
    public static void testNamedParameterJdbcTemplate()
    {
        String sql = "INSERT INTO student(id,student_name,email,Dept_No) VALUES(:id,:name,:email,:deptid)";
        Map paramMap = new HashMap<>();
        paramMap.put("id",9);
        paramMap.put("name","Limbo");
        paramMap.put("email","[email protected]");
        paramMap.put("deptid",1);

        namedParameterJdbcTemplate.update(sql,paramMap);
    }

    /**
     * 使用具名参数的时候,可以用update(java.lang.String sql,org.springframework.jdbc.core.namedparam.SqlParameterSource paramSource)进行更新操作
     * 直接将一个对象作为参数
     * 1.SQL语句中的参数名和类的属性一致
     * 2.使用SqlParameterSource的BeanPropertySqlParameterSource  实现类作为参数
     */

    public static void testNamedParameterJdbcTemplate2()
    {
        String sql = "INSERT INTO student(id,student_name,email,Dept_No) VALUES(:id,:studentName,:email,:deptId)";

        Student student = new Student();
        student.setStudentName("wyh");
        student.setId(10);
        student.setEmail("[email protected]");
        student.setDeptId(1);

        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(student);
        namedParameterJdbcTemplate.update(sql,paramSource);
    }

    public static void main(String[] args) {
        testNamedParameterJdbcTemplate2();
    }
}


以上就是用JdbcTemplet和NamedParameterJdbcTemplate实现的增删改查,当然需要取出一个实体的时候可以这样写

StudentDao.java

package cn.limbo.spring.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 * Created by Limbo on 16/7/15.
 */
@Repository
public class StudentDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Student get(int id)
    {
        String sql = "SELECT * FROM student WHERE id = ?";
        RowMapper rowMapper = new BeanPropertyRowMapper<>(Student.class);
        Student student = jdbcTemplate.queryForObject(sql,rowMapper,1);
        return student;
    }
}



你可能感兴趣的:(Spring)