Spring Boot - Database Configuration

Spring Boot - Database Configuration

Integrate JdbcTemplate

  1. pom.xml configure maven dependencies
  2. application.properties configures the data source
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=1
spring.datasource.initial-size=1
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800

Practice: Querying the User Table

  • create table user
CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(8) NOT NULL DEFAULT '',
  `age` int(11) NOT NULL,
  `create` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
  • Create user entity
package com.wanye.entity;

/**
 * Created by wanye on 2017/6/3.
 */
public class User {
    private int id;
    private String name;
    private int age;
    private int create;
// 省略get set
}
  • Create UserService and inject JdbcTemplate to implement query method
package com.wanye.service;

import com.wanye.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by wanye on 2017/6/3.
 */
@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> getUserList() {
        return jdbcTemplate.query("select * from user", new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                user.setCreate(resultSet.getInt("create"));
                return user;
            }
        });
    }
}
  • Add Controller and return the result. The
    code snippet is as follows. For how to implement the web interface, please refer to
    @Autowired
    private UserService userService;
    @RequestMapping("/userlist")
    public List<User> getUserList() {
        return userService.getUserList();
    }

Integrate MyBatis

  1. pom.xml configure maven dependencies
  2. application.properties configure mybatis
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- 省略mysql驱动依赖 -->
#关于mapper文件位置和entity类位置,大家需要按自己需要进行修改
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
mybatis.type-aliases-package=com.wanye.entity

Practice: query specified user information by user id

  • Create mapper interface @Mapper
package com.wanye.mapper;

import com.wanye.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * Created by wanye on 2017/6/3.
 */
@Repository
@Mapper
public interface UserMapper {
    public User getUserById(int id);
}
  • Create mapper.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- namespace要指向定义的mapper接口 -->
<mapper namespace="com.wanye.mapper.UserMapper">
<!-- id即mapper接口中的具体方法名 -->
<!-- resultType即方法返回值-->
    <select id="getUserById" resultType="com.wanye.entity.User">
        SELECT * FROM USER WHERE id = #{id}
    </select>
</mapper>
  • Implement the query method and add it to the userservice class
    @Autowired
    private UserMapper userMapper;
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }
  • Return Json result in controller, omit

affairs

Business Concepts and Principles

  1. Definition: From the database point of view, it is a set of SQL instructions, either all of which are executed successfully. If one of the instructions is executed incorrectly for some reason, all the previously executed instructions will be undone. To put it more simply: either all executions are successful, or undo is not executed.
  2. Java transaction: Since the concept of transaction comes from the database, what is the Java transaction? What is the connection between? In fact, if a Java application system wants to operate the database, it is realized through JDBC. Adding, modifying, and deleting are achieved indirectly through corresponding methods, and the control of the transaction is also transferred to the Java program code accordingly. Therefore, transactions for database operations are conventionally referred to as Java transactions.
  3. Implementation principle (stand-alone transaction): JDBC transaction is controlled by Connection object. The JDBC Connection interface ( java.sql.Connection ) provides two transaction modes: autocommit and manual commit. java.sql.Connection provides the following methods for controlling transactions:
            public void setAutoCommit(boolean)  
            public boolean getAutoCommit()  
            public void commit()  
            public void rollback()  

When using JDBC transactions, you can combine multiple SQL statements into a single transaction. One disadvantage of JDBC transactions is that the scope of the transaction is limited to a database connection. A JDBC transaction cannot span multiple databases.
4. JTA (Java Transaction API) transaction (multi-machine transaction), implemented through xa, requires driver support. Transactions can span multiple databases or multiple DAOs, with many pits and complicated usage.
5. Container transactions, provided by the j2ee container, are basically implemented based on JTA. Limited to EJB applications.

How to configure transactions

  1. Use the annotation @EnableTransactionManagement to enable transaction support, it is recommended to add it to the startup class, for example
@EnableTransactionManagement
@SpringBootApplication
public class Start {
    public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }
}
  1. Add the annotation @Transactional to the Service method that accesses the database.

Practice: Copy user information and change the name of the original user to xiaoming

  1. Case1: normal (add 1 record name=xiaohong, update 1 record name=xiaoming)
  2. Case2: Exception (name length exceeds varchar(8)) causes rollback
userService.java
@Transactional
public void copyUser(long id, String name) {
    User user = getUserById(id);
    int i = jdbcTemplate.update("insert INTO USER (name,age,`CREATE`) VALUES (?,?,?)", new Object[]{user.getName(), user.getAge(), user.getCreate()});
    logger.info("复制成功: i=" + i + " name=" + name + " id=" + id);
    i = jdbcTemplate.update("update USER SET name=? where id=?", new Object[]{name, user.getId()});
    logger.info("更新成功:i=" + i + " name=" + name + " id=" + id);
}
userController.java
@RequestMapping("/user/cp/{id}/{name}")
public List<User> cpUser(@PathVariable("id") long id, @PathVariable("name") String name) {
    userService.copyUser(id, name);
    return userList();
}

Please verify by yourself that if the length of {name} exceeds 8 bytes, the successfully copied data will be rolled back. In addition, the mysql database engine needs to use InnoDB, not all engines support transactions, you can query the database engine related information.

Summarize

This article explains Spring Boot's integration of JdbcTemplate and mybatis, and introduces and focuses on transaction processing and configuration. This article does not mention paging queries and database connection pools. I think the focus of paging queries is how to encapsulate the paging algorithm, not Spring Boot's concern The key point of this is that you can implement it yourself. In addition, the commonly used database connection pools are c3p0/dbcp/tomcat-jdbc/HikariCP. By the way, to change the data source in Spring Boot, you only need to add spring. datasource.type can be configured, for example:

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

finally

If you think my article is useful to you, please like and bookmark it. Your support will encourage me to keep creating!
In order to improve everyone's learning effect, a synchronized video course has been recorded, and I hope you can support the video course

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324885369&siteId=291194637