Spring JDBC批量更新操作

我们将在单批次操作中更新student表中的记录。

student表的结果如下 -

CREATE TABLE student(
	id INT NOT NULL AUTO_INCREMENT,
	name VARCHAR(20) NOT NULL,
	age INT NOT NULL,
	PRIMARY KEY(id)
);

语法:

 public void batchUpdate(final List<Student> students) {
        String sql = "update Student set age = ? where id = ?";
        int[] updateCounts = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                System.out.println("i = " + i);
                preparedStatement.setInt(1, students.get(i).getAge());
                preparedStatement.setInt(2, students.get(i).getId());
            }
            public int getBatchSize(){
                return students.size();
            }
        });
        System.out.println("Records updated!");
    }

在上面语法中 -

  • SQL - 更新语句以更新学生的年龄。
  • BatchPreparedStatementSetter - 批量执行者,在PerparedStatement对象中设置每个项目的值,由学生对象和索引i列出。 getBatchSize()返回批处理的数量。
  • jdbcTemplateObject - NamedParameterJdbcTemplate对象来更新数据库中的学生对象。
  • updateCounts - int数组包含每个更新查询更新的行计数(数量)。

创建项目

要了解上面提到的Spring JDBC相关的概念,这里创建一个项目用来演示如何执行批量更新。打开Eclipse IDE,并按照以下步骤创建一个名称为:BatchOperation 的Spring应用程序项目。

步骤说明

  1. 参考第一个Spring JDBC项目来创建一个Maven项目 - http://blog.csdn.net/q343509740/article/details/79473726
  2. 更新bean配置并运行应用程序。

完整的项目结构如下所示 -

文件 : pom.xml 的内容 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ray</groupId>
    <artifactId>BatchOperation</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>BatchOperation</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>

由于使用mysql5.1.45版本会出现Could not retrieve transaction read-only status from server问题,我果断使用5.1.9版本。

以下是数据访问对象接口文件:StudentDAO.java的代码内容:

/**
 * Created by 2018 on 2018/3/8 0008.
 */
public interface StudentDAO {

    public void setDataSource(DataSource dataSource);

    public List<Student> listStudents();

    public void create(String name, Integer age);

    public void batchUpdate(final List<Student> students);
}

以下是文件:Student.java的代码内容:

/**
 * Created by 2018 on 2018/3/8 0008.
 */
public class Student {
    private Integer age;
    private String name;
    private Integer id;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getId() {
        return id;
    }

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

以下是文件:StudentMapper.java的代码内容:

/**
 * Created by 2018 on 2018/3/8 0008.
 */
public class StudentMapper implements RowMapper<Student>{

    public Student mapRow(ResultSet resultSet, int i) throws SQLException {
        Student student = new Student();
        student.setId(resultSet.getInt("id"));
        student.setName(resultSet.getString("name"));
        student.setAge(resultSet.getInt("age"));
        return student;
    }
}

以下是文件:StudentJDBCTemplate.java的代码内容:

/**
 * Created by 2018 on 2018/3/8 0008.
 */
public class StudentJDBCTemplate implements StudentDAO{

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public List<Student> listStudents() {
        String sql = "select * from student";
        List<Student> students = jdbcTemplate.query(sql,new StudentMapper());
        return  students;
    }

    public void create(String name, Integer age) {
        String insertQuery = "insert into student(name, age) values(?,?)";
        jdbcTemplate.update(insertQuery,name,age);
        System.out.println("Created Record Name = " + name + " Age = " + age);
        return;
    }

    public void batchUpdate(final List<Student> students) {
        String sql = "update Student set age = ? where id = ?";
        int[] updateCounts = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                System.out.println("i = " + i);
                preparedStatement.setInt(1, students.get(i).getAge());
                preparedStatement.setInt(2, students.get(i).getId());
            }
            public int getBatchSize(){
                return students.size();
            }
        });
        System.out.println("Records updated!");
    }
}

以下是程序执行入口文件:MainApp.java的代码内容:

/**
 * Created by 2018 on 2018/3/8 0008.
 */
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");
        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

        System.out.println("------Records Creation ------");
        studentJDBCTemplate.create("Maxsu",21);
        studentJDBCTemplate.create("Curry",22);
        studentJDBCTemplate.create("Weiwei",25);

        List<Student> initialStudents = studentJDBCTemplate.listStudents();
        System.out.println("Initial Students");
        for (Student student2: initialStudents
                ) {
            System.out.print("ID : " + student2.getId());
            System.out.println(",Age : " + student2.getAge());
        }

        Student student = new Student();
        student.setId(1);
        student.setAge(23);

        Student student1 = new Student();
        student1.setId(3);
        student1.setAge(23);

        List<Student> students = new ArrayList<Student>();
        students.add(student);
        students.add(student1);

        studentJDBCTemplate.batchUpdate(students);

        List<Student> updateStudents = studentJDBCTemplate.listStudents();
        System.out.println("Updated Students");
        for (Student student3:updateStudents
             ) {
            System.out.print("ID : " + student3.getId());
            System.out.println(", Age : " + student3.getAge());
        }

    }
}

以下是Bean和数据库配置文件:application-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--Initialization for data source-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--Definition for studentJDBCTemplate bean-->
    <bean id="studentJDBCTemplate" class="com.ray.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

注意: application-beans.xml 文件的位置是:{workspace}/fistapp/src/main/java 目录,如果放置错了,程序可能会因为找不到此配置文件而出错。

完成创建源代码和bean和数据库连接信息的文件配置后,运行应用程序。这里先简单说明一下运行的步骤,在项目名称(BatchOperation)上点击右键,在弹出的菜单中选择:【Run As】-> 【Maven test】

在运行测试成功后,应该会输出类似以下内容(含有 BUILD SUCCESS 的信息) 。
接下来,点击类文件:MainApp.java 选择【Run As】->【Java Application】,如果应用程序一切正常,这将打印以下消息:

"C:\Program Files\Java\jdk1.8.0_161\bin\java" -Didea.launcher.port=7532 -Didea.launcher.bin.path=F:\soft\idea\ideaIU-2016.3.win\bin -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_161\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\rt.jar;C:\Users\2018\IdeaProjects\BatchOperation\target\classes;F:\drive\MVN\mysql\mysql-connector-java\5.1.9\mysql-connector-java-5.1.9.jar;F:\drive\MVN\org\springframework\spring-jdbc\4.1.0.RELEASE\spring-jdbc-4.1.0.RELEASE.jar;F:\drive\MVN\org\springframework\spring-beans\4.1.0.RELEASE\spring-beans-4.1.0.RELEASE.jar;F:\drive\MVN\org\springframework\spring-core\4.1.0.RELEASE\spring-core-4.1.0.RELEASE.jar;F:\drive\MVN\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;F:\drive\MVN\org\springframework\spring-tx\4.1.0.RELEASE\spring-tx-4.1.0.RELEASE.jar;F:\drive\MVN\org\springframework\spring-context\4.1.4.RELEASE\spring-context-4.1.4.RELEASE.jar;F:\drive\MVN\org\springframework\spring-aop\4.1.4.RELEASE\spring-aop-4.1.4.RELEASE.jar;F:\drive\MVN\aopalliance\aopalliance\1.0\aopalliance-1.0.jar;F:\drive\MVN\org\springframework\spring-expression\4.1.4.RELEASE\spring-expression-4.1.4.RELEASE.jar;F:\soft\idea\ideaIU-2016.3.win\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.ray.MainApp
三月 08, 2018 10:19:34 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@685f4c2e: startup date [Thu Mar 08 22:19:34 CST 2018]; root of context hierarchy
三月 08, 2018 10:19:34 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [application-beans.xml]
三月 08, 2018 10:19:35 下午 org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
信息: Loaded JDBC driver: com.mysql.jdbc.Driver
------Records Creation ------
Initial Students
ID : 1,Age : 21
ID : 2,Age : 22
ID : 3,Age : 25
i = 0
i = 1
Records updated!
Updated Students
ID : 1, Age : 23
ID : 2, Age : 22
ID : 3, Age : 23

Process finished with exit code 0

数据库中的student表中的数据被修改为:


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页