spring与jdbc配置搭配

1.创建一个测试类项目,并导入相应的包

2.在项目根目录下添加配置文件和相应的测试类
这里写图片描述

配置文件beans.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" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"     
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
       <!-- 将数据源文件配置引入 -->
       <context:property-placeholder location="classpath:db.properties"/>

       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${driverClassName}"/>
            <property name="url" value="${url}"></property>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
            <!-- 连接池启动时的初始值 -->
            <property name="initialSize" value="${initialSize}"/>
            <!-- 连接池的最大值 -->
            <property name="maxActive" value = "${maxActive}"/>
            <!-- 最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接释放一部分,一直减少到maxIdle为止 -->
            <property name="maxIdle" value="${maxIdle}"/>
            <!-- 最小空闲值,当空闲连接少于阔值时,连接池就会预申请一些连接,以免洪峰来时来不及申请 -->
            <property name="minIdle" value="${minIdle}"/>
       </bean>

       <!-- spring为我们提供的专门针对数据源的事务管理器 -->
       <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
       </bean>
       <!-- 启动@Transactional注解,将来哪个组件方法带有该标记就会切入tx事务管理功能 -->
       <tx:annotation-driven transaction-manager="txManager"/>

       <!-- 采用自动扫描的方式交给spring管理 -->
       <context:component-scan base-package="cn.itcast"/>
</beans>

db.properties文件内容为

driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/day12?useUnicode\=true&amp;characterEncoding\=utf-8&amp;zeroDateTimeBehavior\=convertToNull
username=root
password=1234567
initialSize=1
maxActive=500
maxIdle=2
minIdle=1

创建实体类和实体映射类

package cn.itcast.bean;

public class Persion {
    private int id;
    private String username;
    private String password;
    private String email;

    public Persion(){}

    public Persion(String username, String password, String email) {
        super();
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

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

}

创建接口和接口的实现类

package cn.itcast.serviece;

import java.util.List;

import cn.itcast.bean.Persion;

public interface PersionService {
    /**
     * 保存Persion
     */
    public void save(Persion persion);

    /**
     * 获取Persion
     */
    public Persion getPersion(int id);

    /**
     * 获取所有的Persion
     */
    public List<Persion> getAllPersion();

    /**
     * 修改Persion
     */
    public void updatePersion(Persion persion);

    /**
     * 删除Persion
     */
    public void deletePersion(int id);
}

JDBCTemplate的使用

package cn.itcast.serviece.impl;

import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bean.Persion;
import cn.itcast.serviece.PersionService;
/**
 * 1.@Transactional添加事物,默认保证方法在同一个事物中执行
 * 2.通过dataSource的setter方法,在运行时注入一个dataSouce对象,然后根据这个对象创建一个JdbcTemplate对象 
 * @author thinkpad
 *
 */
@Transactional
@Service
public class PersionServiceBean implements PersionService {
    // private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
     /** 
     * 增加、修改、删除都是使用的JdbcTemplate的update方法。 
     * update方法中第一个参数是sql语句,未知的值用占位符?代替 
     * 第二个参数是一个Object数组。数组里面的各项是上面的占位符的值 
     * 第三个参数是一个int数组。数组的各项是第二个参数中的值在数据库中的类型 
     */  
    public void save(Persion persion) {
        jdbcTemplate.update(
                "insert into user(username,password,email) values (?,?,?)",
                new Object[] { persion.getUsername(), persion.getPassword(),
                        persion.getEmail() }, new int[] {
                        java.sql.Types.VARCHAR, java.sql.Types.VARCHAR,
                        java.sql.Types.VARCHAR });
    }
    /** 
     * 根据id获取单个数据是通过queryForObject方法 
     * 这个方法前面三个参数都与update方法一样 
     * 第四个参数是一个org.springframework.jdbc.core.RowMapper接口的对象 
     * 实现RowMapper接口,必须实现里面的mapRow(ResultSet rs, int rowNum)方法 
     * 这个方法是通过ResultSet把一条记录放到一个实体类对象中,并返回这个实体类对象 
     */ 
    public Persion getPersion(int id) {
        Persion persion = (Persion) jdbcTemplate.queryForObject(
                "select * from user where id=?", new Object[] { id },
                new int[] { java.sql.Types.INTEGER }, new PersionRowMapper());
        return persion;
    }
    /** 
     * 通过一条没有占位符的select语句来查询多条记录,并返回一个List集合 
     * query方法里面的两个参数 
     * 第一个是select语句 
     * 第二个是RowMapper接口的对象 
     */ 
    @SuppressWarnings("unchecked")
    public List<Persion> getAllPersion() {
        return (List<Persion>) jdbcTemplate.query("select * from user",
                new PersionRowMapper());
    }

    public void updatePersion(Persion persion) {
        jdbcTemplate.update("update user set username=? where id=?",
                new Object[] { persion.getUsername(), persion.getId() },
                new int[] { java.sql.Types.VARCHAR, java.sql.Types.INTEGER });
    }

    public void deletePersion(int id) {
        jdbcTemplate.update("delete from user where id=?", new Object[] { id },
                new int[] { java.sql.Types.INTEGER });
    }

}
package cn.itcast.serviece.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import cn.itcast.bean.Persion;

public class PersionRowMapper implements RowMapper {

    public Object mapRow(ResultSet rs, int index) throws SQLException {
        Persion persion = new Persion();
        persion.setId(rs.getInt("id"));
        persion.setUsername(rs.getString("username"));
        persion.setPassword(rs.getString("password"));
        persion.setEmail(rs.getString("email"));
        return persion;
    }

}

测试类

package cn.itcast.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Persion;
import cn.itcast.serviece.PersionService;

public class PersionTest {
    @Test
    public void demoTest() {
        ApplicationContext atc = new ClassPathXmlApplicationContext("beans.xml");
        PersionService persionService = (PersionService) atc
                .getBean("persionServiceBean");
        persionService.save(new Persion("tom", "123", "[email protected]"));
    }

    @Test
    public void demoTest1() {
        ApplicationContext atc = new ClassPathXmlApplicationContext("beans.xml");
        PersionService persionService = (PersionService) atc
                .getBean("persionServiceBean");
        Persion persion = persionService.getPersion(4);
        System.out.println(persion.getUsername());
    }

    @Test
    public void demoTest2() {
        ApplicationContext atc = new ClassPathXmlApplicationContext("beans.xml");
        PersionService persionService = (PersionService) atc
                .getBean("persionServiceBean");
        List<Persion> list = persionService.getAllPersion();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).getUsername() + ":"
                    + list.get(i).getPassword() + ":" + list.get(i).getEmail());
        }
    }

    @Test
    public void demoTest3(){
        ApplicationContext atc = new ClassPathXmlApplicationContext("beans.xml");
        PersionService persionService = (PersionService) atc
                .getBean("persionServiceBean");
        Persion persion = persionService.getPersion(1);
        persion.setUsername("zhaohailong");
        persionService.updatePersion(persion);
    }

    @Test
    public void demoTest4(){
        ApplicationContext atc = new ClassPathXmlApplicationContext("beans.xml");
        PersionService persionService = (PersionService) atc
            .getBean("persionServiceBean");
        persionService.deletePersion(3);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32027105/article/details/78570947