在java中,数据持久化有几种方式,spring自带的jdbctemplate,还有mybatis,JPA,这几种方式中spring自带的jdbctemplate要简单一些,它虽然没有MyBatis那么方便,但是比起最开始的Jdbc已经强了很多了,它没有MyBatis功能那么强大,当然也意味着它的使用比较简单,事实上,JdbcTemplate算是最简单的数据持久化方案了,下面我们来看看如何实现的

创建项目

创建spring boot项目,除了导入web依赖,还需要数据库驱动依赖和数据库连接的依赖,在我们创建项目时,选择下面图片中的选项

tidb springboot 整合 springboot整合jdbctemplate_bc


项目创建完后导入数据库连接池依赖,这里我们导入的是spring boot的druid

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhouym</groupId>
    <artifactId>jdbctemplate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jdbctemplate</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.27</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

项目创建完成后,需要在application.properties中配置数据源信息

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///tb_user?useUnicode=true&characterEncoding=UTF-8

下面我们就来使用,做一个简单的crud,在增,删,改中都是update方法,查询是query方法,我们先创建一个javabean,对应数据库中的字段
User类

package com.zhouym.jdbctemplate.javabean;

/**
 * 〈〉
 *
 * @author zhouym
 * @create 2019/8/10
 * @since 1.0.0
 */
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String address;
    private String hobby;
    private String password;
    private String salt;

    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;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getPassword() {
        return password;
    }

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

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public User() {
    }

    public User(Integer id, String name, Integer age, String address, String hobby, String password, String salt) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
        this.hobby = hobby;
        this.password = password;
        this.salt = salt;
    }

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

然后我们在service中处理业务逻辑,在UserService类中注入JdbcTemplate

package com.zhouym.jdbctemplate.service;

import com.zhouym.jdbctemplate.javabean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 〈〉
 *
 * @author zhouym
 * @create 2019/8/10
 * @since 1.0.0
 */
@Service
public class UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<User> query() {
        return jdbcTemplate.query("select * from tb_user", new BeanPropertyRowMapper<>(User.class));
    }

    public int addUser(User user){
        return jdbcTemplate.update("insert into tb_user(name,age,address,hobby,password,salt) " +
                "values (?,?,?,?,?,?)",
                user.getName(),user.getAge(),user.getAddress(),user.getHobby(),user.getPassword(),user.getSalt());
    }

    public int updateUser(User user){
        return jdbcTemplate.update("update tb_user set name = ? where id = ?",user.getName(),user.getId());
    }

    public int deleteUser(User user){
        return jdbcTemplate.update("delete from tb_user where id = ?",user.getId());
    }
}

在上面的查询中,如果数据库中的字段与实体类的属性一一对应,可以使用BeanPropertyRowMapper,我们可以点进去看一下

tidb springboot 整合 springboot整合jdbctemplate_tidb springboot 整合_02


BeanPropertyRowMapper会把传入的泛型Java类的所有属性名称的全小写形式放入mapperFields中

tidb springboot 整合 springboot整合jdbctemplate_User_03


把Java类的属性名转化成下划线分割的形式,如myName会被转化成my_name,这是因为,数据库在设计字段名称的时候,一般都会使用下划线分割形式,也就是my_name。

tidb springboot 整合 springboot整合jdbctemplate_bc_04


所以,如果在使用时,Java类名称要想和数据库字段名称匹配上,必须要把数据库字段名称设计成以下两种中的一种,

数据库字段名设计成全小写的形式,如myname;数据库字段名设计成下划线分割的形式,如my_name;

同时,Java属性名称应该尽量遵循Java编码风格,使用camelCase风格,如myName。

测试类

package com.zhouym.jdbctemplate;

import com.zhouym.jdbctemplate.javabean.User;
import com.zhouym.jdbctemplate.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JdbctemplateApplicationTests {

    @Autowired
    UserService userService;

    @Test
    public void contextLoads() {
        List<User> users = userService.query();
        System.out.println(Arrays.asList(users));
    }

    @Test
    public void test1() {
        User user = new User();
        user.setName("赵磊");
        user.setAge(23);
        user.setAddress("深圳");
        user.setHobby("泡妞");
        user.setPassword("123456");
        user.setSalt("abc");
        try {
            userService.addUser(user);
            System.out.println("添加成功");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test2() {
        User user = new User();
        user.setName("前途无量");
        user.setId(14);
        try {
            userService.updateUser(user);
            System.out.println("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test3() {
        User user = new User();
        user.setId(11);
        try {
            userService.deleteUser(user);
            System.out.println("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}