1. 程式人生 > >【Spring Data Access】SimpleJdbcInsert 使用方法

【Spring Data Access】SimpleJdbcInsert 使用方法

SimpleJdbcInsert使用介紹

SimpleJdbcInsert主要被用來簡化插入操作,

下面我們通過一個簡單的示例來熟悉一下使用:


import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.
BeanPropertySqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import javax.sql.DataSource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author jiangjian */ public class SimpleJdbcInsertSample { public static void main(String[] args)
{ ApplicationContext ac = new AnnotationConfigApplicationContext(Config.class); JdbcTemplate jdbcTemplate = ac.getBean(JdbcTemplate.class); //初始化資料庫 jdbcTemplate.execute("drop table if exists user "); jdbcTemplate.execute("create table user(id int auto_increment primary key, name varchar(40), age int)"
); DataSource dataSource = ac.getBean(DataSource.class); SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource) //必須操作: 這裡我們配置當前作用的table .withTableName("user") //可選操作: 這裡我們可以顯示的配置,我們insert語句中的column的名稱,未被列出的column則不會插入值, // 取各自的預設值 .usingColumns("name", "age") //可選操作: 這裡我們配置table 自動生成的column名稱,如果沒有,則不需要配置, // 此處配置是我們想了解自動生成key的資訊 .usingGeneratedKeyColumns("id"); //方式一 //準備引數 Map<String, Object> insertUser = new HashMap<>(2); insertUser.put("name", "bob"); insertUser.put("age", 26); //呼叫插入,如果不需要了解自動生成欄位的值,則直接呼叫execute方法, Number bobId = simpleJdbcInsert.executeAndReturnKey(insertUser); System.out.println("bob id: " + bobId.longValue()); //方法二 // 不需要呼叫executeAndReturnKey方法,而且傳入的值可以是Map,也可以是SqlParameterSource Number aliceId = simpleJdbcInsert.executeAndReturnKey(new BeanPropertySqlParameterSource(new User("alice", 18))); System.out.println("alice id: " + aliceId.longValue()); //輸出所有使用者 List<User> findUsers = jdbcTemplate.query("select * from user", (rs, rowNum) -> new User(rs.getLong(1), rs.getString(2))); findUsers.forEach(System.out::println); //清理環境 jdbcTemplate.execute("drop table user"); } }

上面的執行結果如下: 在這裡插入圖片描述 首先我們要了解是SimpleJdbcInsert的建立,我們需要配置DataSource, 同時我們也得顯示指定操作對應的table資訊,所以如下是最基本的配置:

SimpleJdbcInsert(dataSource)
        .withTableName("user");

注意到上面的程式碼片段和示例中的區別是示例中指定了具體的 column名稱(通過usingColumns方法),對於上面並沒有顯示的給出操作的column資訊,SimpleJdbInsert則是通過driver提供的metainfo去查詢對應table的column資訊。

最後,我們看到指定自動生成欄位的名稱,通過usingGeneratedKeyColumns完成,如果你的table沒有對應的欄位,或者你不需要了解這些欄位的資訊,則可以選擇忽略這個方法的呼叫。

附: 上面示例其他關聯類的定義

Config.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @author jiangjian
 */
@Configuration
@ComponentScan
@PropertySource("classpath:jdbc.properties")
public class Config {
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        return dataSource;
    }

    /**
     * 這裡定義JdbcTemplate的作用是設定一些資料環境,和SimpleJdbcInsert使用沒有關聯關係
     **/
    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
}

jdbc.properties

spring.datasource.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&autoReconnectForPools=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

User.java

public class User {
    private Long id;
    private String name;
    private int age;

    public User() {
    }

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}