Abstract

The purpose of this article is to document how to integrate JDBC and MyBatis in the SpringBoot project. I will use simple usage and test cases in the integration. After all, the purpose of this article is to integrate, not to teach you how to use it. I hope you will bear with me.

General configuration

The entity classes and configurations required to integrate JDBC and MyBatis are described below

The 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;
Copy the code

Entity class

Add a simple User entity class for JDBC and MyBatis usage and testing below. Add a toString method to make it easier to see the results when testing.

public class User {

    private Integer id;

    private String username;

    private String address;

    public Integer getId(a) { return id; }

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

    public String getUsername(a) { return username; }

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

    public String getAddress(a) { return address; }

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

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", address='" + address + '\' ' +
                '} '; }}Copy the code

Maven configuration

SQL > select * from druid; SQL > select * from druid;

<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>
Copy the code

Database Configuration

The database properties configuration is definitely missing.

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.username=username Spring. The datasource. Password = password spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / mydatabaseCopy the code


Integration of JDBC

Maven rely on

Add JDBC dependencies provided by SpringBoot

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
Copy the code

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

    /** * only when class attributes and database fields do not match@return* /
    public List<User> getAllUserFirst(a) {
        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);
                returnuser; }}); }/** * when the class attribute corresponds to the database field, it is much simpler than above */
    public List<User> getAllUserSecond(a) {
        return jdbcTemplate.query("select * from user;".newBeanPropertyRowMapper<>(User.class)); }}Copy the code

It is important to remember that JDBC is created, modified, and deleted using the Update method. For a query, you use Query. If the database fields and entity class attributes are inconsistent, you need to use the above code query method 1 if the database fields and entity class attributes are consistent, you can use the above code query method 2, simple and quick.

test

After finishing, of course, there is no test, the test class is as follows:

@SpringBootTest
class JdbcApplicationTests {

    @Autowired
    UserService userService;

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

    public void queryUsers(a) { List<User> allUserFirst = userService.getAllUserFirst(); System.out.println(allUserFirst); }}Copy the code


Integration of MyBatis

MyBatis, the most popular persistent layer framework, SSM every day, heard the ears are calluses. MyBatis integration is probably the most used, integration is as follows:

Maven rely on

Check out the Maven repository for versions

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
Copy the code

Scanning Mapper

Need to offer SpringBoot scanned mapper path, my bag is scanning path for cn. Colablog.. Mybatis mapper way one: add a configuration items

@Configuration
@MapperScan(basePackages = "cn.colablog.mybatis.mapper")
public class MyBatisConfig {}Copy the code

Method 2: Directly configure the configuration on Application

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

Mapper mapping

UserMapper interface

The Mapper package cn. Colablog.. Mybatis Mapper directory to add UserMapper interface

@Mapper
public interface UserMapper {
    List<User> getAllUser(a);
}
Copy the code

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ? >

      
<mapper namespace="com.colablog.mybatis.mapper.UserMapper">
    <select id="getAllUser" resultType="com.colablog.mybatis.bean.User">
        select * from user
    </select>
</mapper>
Copy the code

There are three kinds of storage ways: a way (default) SpringBoot default find Mapper. XML is in the resources directory, such as mapping UserMapper the path of the interface in the Java directory of cn. Colablog.. Mybatis Mapper. So UserMapper. XML needs under the resources directory. Cn colablog.. Mybatis mapper. Note: If you are using the IDEA development tool, the add directory under resource cannot be added like this:

cn.colablog.mybatis.mapper

Method 2 Configure the storage path in the Properties file:

mybatis.mapper-locations=classpath:/mapper/*.xml
Copy the code

Storage location:

To configure resource in pom. XML, you need to load the XML file in the Java directory:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>.</build>
Copy the code

This way you can store the UserMapper interface in the same directory as the following:

That’s the end of the article! I will continue to write articles about SpringBoot, but if you are interested, check out my first two articles about SpringBoot Web. Thank you for reading this article. If you have any questions or better suggestions, please leave a comment below, Thanks – (· ω ·) Blue.

Personal blog: colablog.cn/

If my article helps you, you can follow my wechat official number and share the article with you as soon as possible