您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring_使用JdbcTemplate和JdbcDaoSupport

bubuko 2022/1/25 19:46:19 java 字数 31372 阅读 1066 来源 http://www.bubuko.com/infolist-5-1.html

1.JdbcTemplate?简化 JDBC 模板查询 ①每次使用都创建一个 JdbcTemplate 的新实例, 这种做法效率很低下.②JdbcTemplate 类被设计成为线程安全的, 所以可以再 IOC 容器中声明它的单个实例, 并将这个实例注入到所有的 DAO 实例中.③JdbcTempla ...

1.JdbcTemplate 简化 JDBC 模板查询

①每次使用都创建一个 JdbcTemplate 的新实例, 这种做法效率很低下.
②JdbcTemplate 类被设计成为线程安全的, 所以可以再 IOC 容器中声明它的单个实例, 并将这个实例注入到所有的 DAO 实例中.
③JdbcTemplate 也利用了 Java 1.5 的特定(自动装箱, 泛型, 可变长度等)来简化开发
④Spring JDBC 框架还提供了一个 JdbcDaoSupport 类来简化 DAO 实现. 该类声明了 jdbcTemplate 属性, 它可以从 IOC 容器中注入, 或者自动从数据源中创建.

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.0.xsd">

    <context:component-scan base-package="com.aff.spring.jdbc"></context:component-scan>
    <!-- 导入资源文件 -->
    <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>

 

 

db.properties

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

jdbc.initPoolSize=5
jdbc.maxPoolSize=20

 

JDBCTest.java

package com.aff.spring.jdbc;

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

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   EmployeeDAO employeeDAO;
    private DepartmentDAO departmentDAO;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
         employeeDAO = ctx.getBean(EmployeeDAO.class);
         departmentDAO = ctx.getBean(DepartmentDAO.class);
         namedParameterJdbcTemplate =ctx.getBean(NamedParameterJdbcTemplate.class);
    }
    
    /**
     *  使用具名参数时 , 可以使用 NamedParameterJdbcTemplate.update(String sql, SqlParameterSource paramSource) 
     *  进行操作,
     *  1.SQL参数名和类的属性名一致
     *  2.使用 SqlParameterSource 的BeanPropertySqlParameterSource 实现类作为参数
     */
    @Test
    public void  testNamedParameterJdbcTemplate2(){
        String sql  ="insert into  employees(last_name,email,dept_id) values(:lastName,:email,:deptId)";
        Employee  employee = new Employee();
        employee.setLastName("hxl");
        employee.setEmail("hxl@qq.com");
        employee.setDeptId(4);
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee);;
        
        namedParameterJdbcTemplate.update(sql, paramSource);
    }
    
    /**
     * 可以为参数气起名字。
     * 好处: 若有多个参数, 则不用去对应位置, 直接对应参数名, 便于维护
     *  缺点: 很麻烦
     */
    @Test
    public void  testNamedParameterJdbcTemplate(){
        String sql  ="insert into  employees(last_name,email,dept_id) values(:ln,:email,:deptid)";
         
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("ln", "hh");
        paramMap.put("email", "hh@qq.com");
        paramMap.put("deptid", 3);
        
        namedParameterJdbcTemplate.update(sql, paramMap);
    }
    

    @Test
    public  void  testDepartmentDao(){
        System.out.println(departmentDAO.get(1));
        //Department [id=1, name=财务部]

        
    }
    
    @Test
    public void   testEmployeeDAO(){
        System.out.println(employeeDAO.get(7));
        //Employee [id=7, lastName=jack, email=222@QQ.COM, department=null]

        
    }
    
    /**
     * 获取单个列的值, 或做统计查询 
     * 使用JdbcTemplate.queryForObject(String sql, Class<Long> requiredType) 
     */
    @Test
    public void  testQueryForObject2(){
        String sql ="select count(id) from employees";
        Long count = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(count);
        //27
    }
    
    
    /**
     * 查到实体类的集合
     * 注意 调用的不是queryForList 方法
     */
    @Test
    public void  testQueryForList(){
        String sql =  "select id, last_name  lastName ,email  from employees where id<?";
        RowMapper<Employee> rowMapper  = new BeanPropertyRowMapper<>(Employee.class);
        List<Employee> employees = jdbcTemplate.query(sql, rowMapper,3);
        System.out.println(employees);
        //[Employee [id=1, lastName=Tom, email=tom@163.com, department=null], 
        //Employee [id=2, lastName=Jerry, email=jerry@126.com, department=null]]
    }
    
    
    /**
     * 从数据库中获取一条记录, 实际得到对应的对象
     * 注意不是调用JdbcTemplate.queryForObject(String sql, Class<Employee> requiredType, Object... args)
     * 而是调用.JdbcTemplate.queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
     * 1.其中的 RowMapper 指定如何去映射结果集的行,常用的实现类为BeanPropertyRowMapper
     * 2.使用SQL 中列的别名 完成类名和类的属性名的映射, 如:last_name  lastName
     * 3.不支持级联属性,JdbcTemplate 到底是一个JDBC 的小工具, 而不是ORM框架
     */
    @Test
    public void testQueryForObject(){
        String sql =  "select id, last_name  lastName ,email ,dept_id as\"department.id\" from employees where id=?";
        RowMapper<Employee> rowMapper  = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee =     jdbcTemplate.queryForObject(sql, rowMapper,1);
                
        System.out.println(employee);
        //Employee [id=1, lastName=Tom, email=tom@163.com, department=null]

        
    }
    
    
    /**
     * 执行批量的更新: 批量的 insert update  delete
     * 最后一个一个参数 是Object[] 的list 类型 ,因为 修改一条记录需要一个Object数组,多条记录,就需要多个Objec数组,构成的list 集合
     */
    @Test
    public void testBatchUpdate() {
        String sql ="insert into employees(last_name, email, dept_id) values(?,?,?)";
        
        List<Object[]> batchArgs =  new ArrayList<Object[]>();
        batchArgs.add(new Object[]{"aa","aa@qq.com",2});
        batchArgs.add(new Object[]{"bb","bb@qq.com",3});
        batchArgs.add(new Object[]{"cc","cc@qq.com",3});
        batchArgs.add(new Object[]{"dd","dd@qq.com",3});
        
        //一条记录三个字段构成一个Object数组,多条记录构成Object 数组的集合
        jdbcTemplate.batchUpdate(sql, batchArgs);
        
    }

    /**
     * 执行 insert update delete
     */
    @Test
    public void testUpdate() {
        String sql = "update employees set  last_name = ? where id=?";
        jdbcTemplate.update(sql, "jack", 7);
    }

    // 测试连接
    @Test
    public void test() throws SQLException {
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource.getConnection());

    }

}

 

EmployeeDAO.java

package com.aff.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;

@Repository
public class EmployeeDAO {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Employee get(Integer id) {
        String sql = "select id, last_name  lastName ,email  from employees where id=?";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, id);

        return employee;
    }
}

 

DepartmentDAO.java

package com.aff.spring.jdbc;

import javax.sql.DataSource;

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

//不推荐使用
@Repository
public class DepartmentDAO extends JdbcDaoSupport {
    @Autowired
    private void setDataSource2(DataSource dataSource) {
        setDataSource(dataSource);
    }

    public Department get(Integer id) {
        String sql = "select  id ,dept_name name from departments where id=?";
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);
        return getJdbcTemplate().queryForObject(sql, rowMapper, id);
    }
}

 

 Department.java

package com.aff.spring.jdbc;

public class Department {
    private Integer id ;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer 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 + "]";
    }
    public Department(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public Department() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    

}

 

Employee.java

package com.aff.spring.jdbc;

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer deptId;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getDeptId() {
        return deptId;
    }
    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }
    @Override
    public String toString() {
        return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", deptId=" + deptId + "]";
    }


    
}

目录

技术分享图片

 

Spring_使用JdbcTemplate和JdbcDaoSupport

原文:https://www.cnblogs.com/afangfang/p/12988830.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶