Spring Boot series of JDBC operation database

PS: The original text was first published on WeChat public account: Jongxingzhi (jzman-blog)

Before reading this article, you can read the first few articles:

JDBC (Java Data Base Connectivity, Java database connection), the main purpose is to connect to the database, execute SQL statements, process SQL execution results, etc., start from scratch the learning of JDBC in Spring Boot, the main content is as follows:

  1. Install MySQL
  2. Connect to MySQL
  3. Create database
  4. Dependency and configuration
  5. Entity class
  6. Achieve addition, deletion and modification
  7. Test effect
  8. Multiple data source configuration

Install MySQL

Visit the official website to download the corresponding version of MySQL:

https://dev.mysql.com/downloads/

Here, select the installation package corresponding to the Windows operating system to download, as shown in the following figure:

Then select next to install, after the installation is complete, you can start MySQL.

Connect to MySQL

After installing MySQL, start MySQL, and then use Navicat to connect to MySQL. The new connection is as follows:

Enter the user name, password, etc. and click to test the connection. If the configuration is correct, it will prompt that the connection is successful.

Create database and table

After connecting to MySQL, right-click the connection to create the database db_student as follows:

The corresponding command to create the database is as follows:

CREATE DATABASE `db_student` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_0900_ai_ci';

After creating the database, create a table named student. You can use Navicat to create or use the command. The command to create the table is as follows:

CREATE TABLE `student` (
     `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
     `name` varchar(32) DEFAULT NULL COMMENT '用户名',
     `password` varchar(32) DEFAULT NULL COMMENT '密码',
     `age`  int DEFAULT NULL COMMENT '年龄',
     PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Dependency and configuration

Create a Spring Boot project and add the JDBC and MySQL driver dependencies in its build.gradle file as follows:

dependencies {
    
    
    // jdbc依赖
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    // mysql驱动
    runtime("mysql:mysql-connector-java")
    // ...
}

Then perform the basic configuration of the database in the application.properties file of the project, as follows:

# 数据库用户名
spring.datasource.username=root
# 数据库密码
spring.datasource.password=admin
# JDBC Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JDBC URL
spring.datasource.url=jdbc:mysql://localhost:3306/db_student?serverTimezone=Asia/Shanghai

After the configuration is completed, you can use IDEA's Database tool to test whether the configuration is correct. The test is successful as shown in the figure below:

Entity class

Create a data table studentcorresponding to the data entity class as follows:

/**
 * 实体类
 */
public class Student {
    
    
    private long id;
    private String name;
    private String password;
    private int age;

    public Student() {
    
    
    }

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

    public Student(long id,String name, String password, int age) {
    
    
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
    }

    // setter、getter方法
}

Achieve addition, deletion and modification

CRUD interfaces defined IStudentRepositoryas follows:

/**
 * @Desc: 定义增删查改接口
 * @Author: jzman
 */
public interface IStudentRepository {
    
    
    /**
     * 保存数据
     * @param student 单条student记录
     */
    void save(Student student);

    /**
     * 删除数据
     * @param id 学生id
     */
    void delete(long id);

    /**
     * 更新数据
     * @param student 单条student记录
     */
    void update(Student student);

    /**
     * 查询数据
     * @param name 姓名
     * @return 返回单条记录
     */
    Student findByName(String name);

    /**
     * 查询全部数据
     * @return 返回全部记录
     */
    List<Student> findAll();
}

Creating StudentRepositoryImplimplement IStudentRepositoryinterface CRUD:

/**
 * @Desc: 具体实现
 * @Author: jzman
 */
@Repository
public class StudentRepositoryImpl implements IStudentRepository {
    
    

    public JdbcTemplate mJdbcTemplate;

    /**
     * 构造方法自动装配
     * @param jdbcTemplate JdbcTemplate
     */
    public StudentRepositoryImpl(JdbcTemplate jdbcTemplate) {
    
    
        this.mJdbcTemplate = jdbcTemplate;
    }

    @Override
    public void save(Student student) {
    
    
        mJdbcTemplate.update("INSERT INTO student(name,password,age) values(?,?,?) ",
                student.getName(), student.getPassword(), student.getAge());
    }

    @Override
    public void delete(long id) {
    
    
        mJdbcTemplate.update("DELETE FROM student where id=?", id);
    }

    @Override
    public void update(Student student) {
    
    
        mJdbcTemplate.update("UPDATE student SET name=?,password=?,age=? WHERE id=?",
                student.getName(), student.getPassword(), student.getAge(), student.getId());
    }

    @Override
    public Student findByName(String name) {
    
    
        Object[] args = {
    
    name};
        return mJdbcTemplate.queryForObject("SELECT * FROM student WHERE name=?", args,
                new BeanPropertyRowMapper<Student>(Student.class));
    }

    @Override
    public List<Student> findAll() {
    
    
        return mJdbcTemplate.query("SELECT * FROM student",new BeanPropertyRowMapper<>(Student.class));
    }
}

Test effect

Write a test program for testing, here is to add data as an example, insert two pieces of data as follows:

 * @Desc: StudentRepositoryTests
 * @Author: jzman
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentRepositoryTests {
    
    
    @Autowired
    private IStudentRepository mStudentRepository;

    @Test
    public void testSave(){
    
    
        Student student1 = new Student("躬行之", "111",3);
        Student student2 = new Student(2,"jzman", "123",20);
        mStudentRepository.save(student1);
        mStudentRepository.save(student2);
    }
}

Run testSaveafter using Database tools provided by IDEA, double student table view data table of contents, as follows:

At this point, the data insertion operation is successful, and the same goes for deletion, modification, and query.

Multiple data source configuration

Multi-source configuration arrangement data corresponding to the configuration mainly DataSourceand JdbcTemplate, defining multiple data sources as follows:

/**
 * @Desc: 数据源配置
 * @Author: jzman
 */
@Configuration
public class DataSourceConfig {
    
    

    @Primary
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
    
    
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
    
    
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource){
    
    
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource){
    
    
        return new JdbcTemplate(dataSource);
    }
}

Then configure multiple database connections in the application.properties file, as follows:

# dataSource1
spring.datasource.primary.username=root
spring.datasource.primary.password=admin
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/data_source_one?serverTimezone=Asia/Shanghai


# dataSource1
spring.datasource.secondary.username=root
spring.datasource.secondary.password=admin
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/data_source_two?serverTimezone=Asia/Shanghai

Different sources of data corresponding to the JdbcTemplatedata corresponding to the operation to the data source, specifically with reference to the end view corresponding to source text prompts.

You can follow the public account [Jianxingzhi] to exchange and learn, and reply to the keyword [Spring Boot] to obtain the source link of the corresponding case.

Insert picture description here

Guess you like

Origin blog.csdn.net/jzman/article/details/110453257