zoukankan      html  css  js  c++  java
  • Spring JDBC NamedParameterJdbcTemplate类示例

    org.springframework.jdbc.core.NamedParameterJdbcTemplate类是一个具有基本JDBC操作的模板类,允许使用命名参数而不是传统的’?‘占位符。 这个类代表一个包装的JdbcTemplate,在执行时完成从命名参数占位符替换为JDBC样式’?‘ 占位符。它还允许将值列表扩展到适当数量的占位符。

    使用到的 Student 表的结构如下 -

    CREATE TABLE Student(
       ID   INT NOT NULL AUTO_INCREMENT,
       NAME VARCHAR(20) NOT NULL,
       AGE  INT NOT NULL,
       DESCRIPTION LONGTEXT DEFAULT NULL,
       PRIMARY KEY (ID)
    );
    
    SQL

    类的声明

    以下是org.springframework.jdbc.core.NamedParameterJdbcTemplate接口的声明 -

    public class NamedParameterJdbcTemplate
       extends Object
          implements NamedParameterJdbcOperations
    
    Java

    语法

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("id", id);
    in.addValue("description",  new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB);
    
    String SQL = "update Student set description = :description where id = :id";
    NamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource);
    jdbcTemplateObject.update(SQL, in);
    
    Java

    在上代码中,

    • in - SqlParameterSource对象将参数传递给更新查询。
    • SqlLobValue - 表示SQL BLOB/CLOB值参数的对象。
    • jdbcTemplateObject - NamedParameterJdbcTemplate对象来更新数据库中的Student对象。

    实例项目

    要了解上述与Spring JDBC相关的概念,下面我们编写一个使用NamedParameterJdbcTemplate来更新Student对象。打开Eclipse IDE,并按照以下步骤创建一个Spring应用程序,这里创建一个名称为:NamedParameterJdbcTemplate 的项目。

    步骤说明

    1. 参考第一个Spring JDBC项目来创建一个Maven项目 - http://www.yiibai.com/springjdbc/first_application.html
    2. 更新bean配置并运行应用程序。

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

    以下是Maven配置文件:pom.xml的代码内容:

    <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.yiibai</groupId>
        <artifactId>NamedParameterJdbcTemplate</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
        <name>NamedParameterJdbcTemplate</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.40</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>
    
    XML

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

    package com.yiibai;
    
    import java.util.List;
    import javax.sql.DataSource;
    
    public interface StudentDAO {
        /**
         * This is the method to be used to initialize database resources ie.
         * connection.
         */
        public void setDataSource(DataSource ds);
    
        /**
         * This is the method to be used to list down all the records from the
         * Student table.
         */
        public List<Student> listStudents();
    
        /**
         * This is the method to be used to update a record into the Student table.
         */
        public void updateDescription(Integer id, String description);
    
        public void create(String name, Integer age);
    
    }
    
    Java

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

    package com.yiibai;
    
    public class Student {
        private Integer age;
        private String name;
        private Integer id;
        private String description;
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public Integer getId() {
            return id;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
    Java

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

    package com.yiibai;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import org.springframework.jdbc.core.RowMapper;
    
    public class StudentMapper implements RowMapper<Student> {
        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
            Student student = new Student();
            student.setId(rs.getInt("id"));
            student.setName(rs.getString("name"));
            student.setAge(rs.getInt("age"));
            student.setDescription(rs.getString("description"));
            return student;
        }
    }
    
    Java

    实现类StudentJDBCTemplate.java实现了定义的DAO接口 - StudentDAO.java,以下是文件:StudentJDBCTemplate.java的代码内容:

    package com.yiibai;
    
    import java.util.List;
    import javax.sql.DataSource;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
    import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
    import org.springframework.jdbc.core.namedparam.SqlParameterSource;
    import org.springframework.jdbc.core.simple.SimpleJdbcCall;
    import org.springframework.jdbc.core.support.SqlLobValue;
    import org.springframework.jdbc.support.lob.DefaultLobHandler;
    import java.io.ByteArrayInputStream;
    import java.sql.Types;
    
    public class StudentJDBCTemplate implements StudentDAO {
        private DataSource dataSource;
        private JdbcTemplate jdbcTemplateObject;
    
        public void setDataSource(DataSource dataSource) {
            this.dataSource = dataSource;
            this.jdbcTemplateObject = new JdbcTemplate(dataSource);
        }
    
        public List<Student> listStudents() {
            String SQL = "select * from Student";
            List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
            return students;
        }
    
        public void create(String name, Integer age) {
            // TODO Auto-generated method stub
            String insertQuery = "insert into student (name, age, description) values (?, ?, NULL)";
    
            jdbcTemplateObject.update(insertQuery, name, age);
            System.out.println("Created Record Name = " + name + " Age = " + age);
            return;
        }
    
        public void updateDescription(Integer id, String description) {
    
            MapSqlParameterSource in = new MapSqlParameterSource();
            in.addValue("id", id);
            in.addValue("description", new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB);
    
            String SQL = "update Student set description = :description where id = :id";
            NamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource);
            jdbcTemplateObject.update(SQL, in);
            System.out.println("Updated Record with ID = " + id);
        }
    
    }
    
    Java

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

    package com.yiibai;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import com.yiibai.StudentJDBCTemplate;
    
    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("Suzend", 23);
    
            // 更新描述
            studentJDBCTemplate.updateDescription(1, "This can be a very long text upto 4 GB of size.");
            studentJDBCTemplate.updateDescription(2, "随便写一下描述内容......易百教程(www.yiibai.com) - 专注于IT教程和实例");
    
            System.out.println("------Listing Multiple Records--------");
    
            List<Student> students = studentJDBCTemplate.listStudents();
            for (Student record : students) {
                System.out.print("ID : " + record.getId());
                System.out.print(", Name : " + record.getName());
                System.out.println(", Age : " + record.getAge());
                System.out.println(", Description : " + record.getDescription());
            }
        }
    }
    
    Java

    以下是文件: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-3.0.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?characterEncoding=utf8&useSSL=true" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
        </bean>
    
        <!-- Definition for studentJDBCTemplate bean -->
        <bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
    </beans>
    
    XML

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

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

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

    ------Records Creation--------
    Created Record Name = Maxsu Age = 21
    Created Record Name = Curry Age = 22
    Created Record Name = Suzend Age = 23
    Updated Record with ID = 1
    Updated Record with ID = 2
    ------Listing Multiple Records--------
    ID : 1, Name : Maxsu, Age : 21
    , Description : This can be a very long text upto 4 GB of size.
    ID : 2, Name : Curry, Age : 22
    , Description : 随便写一下描述内容......易百教程(www.yiibai.com) - 专注于IT教程和实例
    ID : 3, Name : Suzend, Age : 23
    , Description : null
  • 相关阅读:
    动态修改 dom 元素的伪类样式
    visual studio 2013 触发挂起事件
    windows phone 切换多语言时,商店标题显示错误的问题
    01、Windows Store APP 设置页面横竖屏的方法
    HTTPS和HTTP的概念和区别
    前端要知道的浏览器原理
    HTTP协议详解
    angular4路由设置笔记
    js正则及常用方法函数总结
    史上最全常用正则表达式大全
  • 原文地址:https://www.cnblogs.com/borter/p/9608489.html
Copyright © 2011-2022 走看看