# Mybatis 初使用

## 一、添加依赖

```markup
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
```

配置mysql：

```
# mysql
spring.datasource.url=jdbc:mysql://localhost/demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```

两种使用Mybatis 的方式

* 第一种： 基于 mybatis 注解的集成
* 第二种：基于 mybatis xml 的集成

## 二、第一种: 基于 mybatis 注解的集成

·

![](/files/-LfnTIdPJKuC5aETfYbq)

bean/DemoUser.java

```java
package com.shuju.testmb.bean;

import java.io.Serializable;
import java.util.Date;

public class DemoUser implements Serializable {
    private Integer id;

    private String name;

    private Date createTime;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", createTime=").append(createTime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}
```

mapper/DemoUserMapper/java

```java
package com.shuju.testmb.mapper;

import com.shuju.testmb.bean.DemoUser;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.type.JdbcType;

@Mapper
public interface DemoUserMapper {

    @Insert(value = "insert into demo_user (name, create_time) values (#{name,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP})")
    int insert(DemoUser record);

    @Select(value = "select id, name, create_time from demo_user where id = #{id,jdbcType=INTEGER}")
    @Results(value = { @Result(column = "create_time", property = "createTime", jdbcType = JdbcType.TIMESTAMP) })
    DemoUser selectByPrimaryKey(Integer id);
}
```

TestmbApplicationTests.java进行测试

```java
package com.shuju.testmb;

import com.shuju.testmb.bean.DemoUser;
import com.shuju.testmb.mapper.DemoUserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestmbApplicationTests {

    @Autowired
    private DemoUserMapper mapper;

    @Test
    public void insert() {
        DemoUser demoUser = new DemoUser();
        demoUser.setName("测试");
        demoUser.setCreateTime(new Date());
        int result = mapper.insert(demoUser);
        System.out.println(result);
    }
}
```

三、基于 mybatis xml 的集成

所涉及文件

![](/files/-LfnTIdT9pODpOs5Zn1T)

bean文件和测试文件保持不变

配置:

```
#mybatis
mybatis.mapper-locations: classpath:mybatis/*.xml
```

mapper/DemoUserMapper/java

```java
package com.shuju.testmb.mapper;

import com.shuju.testmb.bean.DemoUser;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface DemoUserMapper {

    int insert(DemoUser record);

    DemoUser selectByPrimaryKey(Integer id);
}
```

mybatis/DemoUserMapper.xml

```markup
<?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.shuju.testmb.mapper.DemoUserMapper" >
    
    <resultMap id="BaseResultMap" type="com.shuju.testmb.bean.DemoUser" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    </resultMap>
    
    <sql id="Base_Column_List" >
        id, name, create_time
    </sql>

    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" /> from demo_user
        where id = #{id,jdbcType=INTEGER} 
    </select>

    <insert id="insert" parameterType="com.shuju.testmb.bean.DemoUser" >
        insert into demo_user (id, name, create_time)
        values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP})
    </insert>
</mapper>
```

使用测试类测试即可

## 资料

[Mybatis GitHub](https://github.com/mybatis/spring-boot-starter)

[Spring Boot学习笔记——Spring Boot与MyBatis的集成（项目示例）](https://www.cnblogs.com/zifeiy/p/9048536.html)

[springboot(六)：如何优雅的使用mybatis](https://blog.csdn.net/ityouknow/article/details/53063404)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/mybatis/mybatis-chu-shi-yong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
