Database access of Spring Boot

1, Background

Spring boot is a service development framework that integrates service publishing, database management and log management. It is also an all-around helper for microservice development. This chapter describes how to use spring boot to access MySQL database.

2, Build basic environment

1. Install Maven (a lot of guidance documents on the Internet).
2. Create a maven project in eclipse.
3. Configure the warehouse connecting spring boot in pom.xml. The configuration of the dependency part is as follows:


<!-- Add typical dependencies for a web application -->  

4. Configure JDBC connection
Create the configuration file under src/main/resources. Add the following configuration:


3, Develop database access interface

Write database mapper interface by mybatis annotation.

public interface UserMapper
    @Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
    void insertUser(User user);

    @Results(value= {
            @Result(property="userId", column="id"),
            @Result(property="name", column="name"),
            @Result(property="age", column="age")
    @Select("select id, name, age from tbl_user")
    List<User> getUsers();

4, Develop client program calling mapper

public class WSExample
    private UserMapper userMapper;

    @RequestMapping(value="/v1/query-user", method=RequestMethod.GET)
    public List<User> queryUser() 
        return userMapper.getUsers();

5, Add scan mapper annotation on the class of main function

public class App 
    public static void main( String[] args )
        System.out.println( "Hello World!" );, args);

Tags: Spring MySQL Database Mybatis

Posted on Thu, 30 Apr 2020 20:09:29 -0700 by johnh