Three minutes and let Mybatis dance SpringBoot

First, the preparatory work

In order to save these three minutes, first you have to prepare a bootable SpringBoot program, as well as a data table. Order and following synchronization, you can copy my SQL statements directly paste it into your database is running.

CREATE TABLE `tb_user` (
  `user_tel` varchar(100) NOT NULL,
  `user_name` varchar(100)  NULL,
  `user_passwd` varchar(100) NOT NULL,
  PRIMARY KEY (`user_tel`)
) ENGINE=InnoDB ;

Second, adding dependence

  <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.1</version>
  </dependency>
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.18</version>
  </dependency>

At this point, a complete pom file might look like this.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hxl</groupId>
    <artifactId>gongzhonghao</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>gongzhonghao</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
    </dependencies>

</project>

Click Run, SpringBoot try to start a program, and he will report abnormal, you do not have to tell configure the data source.
Here Insert Picture Description
Well, then you configure the data source, adding the database connection information in application.properties project.

spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名称
spring.datasource.username=root(你的用户名)
spring.datasource.password=(你的密码)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Some of the possible class-name blog is com.mysql.jdbc.Driver, and here use com.mysql.cj.jdbc.Driveras Mysql started from 6+ version com.mysql.cj.jdbc.Driver, while the upper is introduced in version 8+.
Here Insert Picture Description
After clicking Run, the above error disappears.

Three, Mapper

Remember when you use Mybatis in plain Java projects do.
1. Create mybatis-config.xml, fill in the connection information.
2. Write the interface, operate on the data crackling after calling getMapper.
At this point it has completed the first step, that is, fill in the information database connections, the next step is to create additions and deletions to change search interface.


@Mapper
public interface UserDao {
    /**
     * 插入一条记录
     * @return
     */
    @InsertProvider(type = InsertSql.class,method ="createInsertSql" )
     int insert(@Param("tel")String tel,@Param("name")String name,@Param("pass")String pass);

    /**
     * 更具tel获取记录
     * @return
     */
    @SelectProvider(type = SelectSql.class,method = "createSelectByTelSql")
    Map<String,String> selectByTel(@Param("tel")String tel);


    class InsertSql{
        public String createInsertSql(){
            return new SQL(){{
                INSERT_INTO("tb_user");
                VALUES("user_tel","#{tel}");
                VALUES("user_name","#{name}");
                VALUES("user_passwd","#{pass}");

            }}.toString();
        }
    }
    class SelectSql{
        public String createSelectByTelSql(){
            return new SQL(){{
                SELECT("*");
                FROM("tb_user");
                WHERE("user_tel=#{tel}");
            }}.toString();
        }
    }
}

Fourth, the test

import com.hxl.gongzhonghao.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
    @Autowired
    UserDao mUserDao;
    @GetMapping("insert")
    public Object insert(){
        String tel ="178484";
        mUserDao.insert(tel,"张三","pass");
      return   mUserDao.selectByTel(tel);
    }
}

Enter your browser to http: // localhost: 8080 / insert can see the following results
Here Insert Picture Description
back to the database, the data is inserted lying here.
Here Insert Picture Description

Pay attention

1.xml configuration
Mybatis provide annotation type and xml type, while the above example using a type annotation, if you want to achieve through xml, first create a file stored mapper directory in the resources folder.
Here Insert Picture Description
And tell mybatis in application.properties, you go to this folder to load.
mybatis.mapper-locations=classpath:mapper/*.xml

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.hxl.gongzhonghao.dao.UserDao">
    <insert id="insert" parameterType="string">
        insert into tb_user values (#{tel},#{name},#{pass})
    </insert>
</mapper>
Published 42 original articles · won praise 7 · views 7753

Guess you like

Origin blog.csdn.net/HouXinLin_CSDN/article/details/104136159