SpringBoot integration jdbc and mybatis

Summary

This article is mainly to record and how to integrate the JDBC MyBatis in SpringBoot project, I will use in the integration and use of a simple test, after all, the purpose of this article is to integrate, rather than teach you how to use. I hope you bear with me.

Spoken arrangement

JDBC integration and integration Here MyBatis will need to add and configure entity classes

Database Table

CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
复制代码

Entity class

Adding a simple User entity class, and used in the following jdbc mybatis use and testing. Add a toString method in order to see the results when the test is relatively simple.

public class User {

    private Integer id;

    private String username;

    private String address;

    public Integer getId() { return id; }

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

    public String getUsername() { return username; }

    public void setUsername(String username) { this.username = username; }

    public String getAddress() { return address; }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
复制代码

Configuring maven

mysql version according to their own version of the database is set druid to provide Ali cloud data sources (understood as the connection pool)

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>8.0.18</version>
</dependency>
复制代码

Database Configuration

Database configuration properties is certainly not less of it.

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydatabase
复制代码

Integration JDBC

maven dependence

Add jdbc rely springboot provided

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
复制代码

use

@Service
public class UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public Integer addUser(User user) {
        return jdbcTemplate.update("insert into user (username,address) values (?,?);",
                user.getUsername(), user.getAddress());
    }

    /**
     * 查询方式一
     * 当类属性和数据库字段不对应时才这样使用
     * @return
     */
    public List<User> getAllUserFirst() {
        return jdbcTemplate.query("select * from user;", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                int id = resultSet.getInt("id");
                String address = resultSet.getString("address");
                String username = resultSet.getString("username");
                user.setId(id);
                user.setUsername(username);
                user.setAddress(address);
                return user;
            }
        });
    }

    /**
     * 查询方式二
     * 当类属性和数据库字段对应时就这样使用啦,比上面的简洁很多
     */
    public List<User> getAllUserSecond() {
        return jdbcTemplate.query("select * from user;", new BeanPropertyRowMapper<>(User.class));
    }
}
复制代码

We should remember what, jdbc whether to add, modify, delete all use updatemethod. The query is using query. If the database fields and attributes are inconsistent entity class, you need to use the above code 查询方式一if the database entity class attribute field and all the same, may be used in the above code 查询方式二, simple and quick.

test

After finishing the course, make up less test it, test classes are as follows:

@SpringBootTest
class JdbcApplicationTests {

    @Autowired
    UserService userService;

    @Test
    public void addUser() {
        User user = new User();
        user.setUsername("johnson2");
        user.setAddress("colablog.cn");
        userService.addUser(user);
    }

    public void queryUsers() {
        List<User> allUserFirst = userService.getAllUserFirst();
        System.out.println(allUserFirst);
    }
}
复制代码

Integration MyBatis

Currently most popular persistence frameworks MyBatis, every day SSM, hear the ears from the cocoon. Integration MyBatis most likely to use, integration is as follows:

maven dependence

Version then you can view the maven repository

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
复制代码

Scan Mapper

The need to provide a path to SpringBoot mapper scanned my bag scan path is cn.colablog.mybatis.mapperone way: a configuration item to add their own

@Configuration
@MapperScan(basePackages = "cn.colablog.mybatis.mapper")
public class MyBatisConfig {
}
复制代码

Second way: directly disposed on Application

@SpringBootApplication
@MapperScan(basePackages = "cn.colablog.mybatis.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}
复制代码

Mapper Mapping

UserMapper Interface

In Mapper package cn.colablog.mybatis.mapperadd UserMapper Interface directory

@Mapper
public interface UserMapper {
    List<User> getAllUser();
}
复制代码

UserMapper.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">
<mapper namespace="com.colablog.mybatis.mapper.UserMapper">
    <select id="getAllUser" resultType="com.colablog.mybatis.bean.User">
        select * from user
    </select>
</mapper>
复制代码

Storing three ways: Method 1 (default) SpringBoot find Mapper.xml under default directory resources, e.g. mapping Userpath in the class java directory cn.colablog.mybatis.mapper. Then UserMapper.xmlyou need to put the resources directory cn.colablog.mybatis.mapper. Note: If you are using IDEA development tools, under the resource directory can not add this to add:

IDEA will help you add this to add a named cn.colablog.mybatis.mapper directory, so you need to add turn-by-directory, storage location as follows:

Second way configuration is stored in a properties file path:

mybatis.mapper-locations=classpath:/mapper/*.xml
复制代码

Storage locations are as follows:

Three ways configuration in pom.xml resource needs to load xml file in java catalog:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        ...
    </build>
复制代码

This way you can UserMapper interfaces and stored in the same directory as the storage location as follows:

Article here came to an end! Next, I will continue to write articles on SpringBoot, interested, then you can look on my previous two SpringBoot Web篇 articles oh. Thank you for reading, at the inadequacies of the article or if better suggestions, please leave a message below, Thanks ♪ (· ω ·) Techno.

Personal blog URL: colablog.cn/

If my articles help to you, I can focus on the public micro-channel number, the first time to share your article

Micro-channel public number

Guess you like

Origin juejin.im/post/5dd205b16fb9a01fe847828e