Spring Boot集成Mybatis

jasmine 于 2020-05-01 发布

1、引入依赖

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

2、resources下增加mybatis-config.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
    </settings>
    <!-- Continue going here -->
</configuration>

3、配置文件增加数据源

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/gf-order?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  config-location: classpath:mybatis-config.xml
  mapper-locations: classpath:mapper/**/*.xml

4、编写业务代码

///---controller
@RestController
@RequestMapping("/gf/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/add/{orderId}")
    public Response<String> add(@PathVariable String orderId) {
        System.out.println("---新增订单接口---id=" + orderId + "---");
        orderService.updateOrder(orderId);
        return Response.success("success");
    }
}


///---service
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    public String updateOrder(String orderId) {
        Order order = new Order();
        order.setGroupID(new Random().nextLong());
        order.setOrderKey(orderId);
        orderMapper.insertOrder(order);
        return "success";
    }
}

///---mapper接口
public interface OrderMapper {

    /**
     * 添加订单
     *
     * @param order 订单对象
     * @return 订单ID
     */
    long insertOrder(Order order);

    /**
     * 更新订单
     *
     * @param order 订单对象
     * @return
     */
    long updateOrderInfo(Order order);
}

5、编写OrderMapper.xml,并放到resources/mapper目录下

<?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.gf.order.mapper.OrderMapper">

    <!-- 添加订单 -->
    <insert id="insertOrder" parameterType="com.gf.order.mapper.po.Order">
        <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="itemID">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT
        `gf-order`
        (
        orderKey,
        groupID,
        actionTime,
        createTime
        )
        VALUES
        (
        #{orderKey},
        #{groupID},
        #{actionTime},
        #{createTime}
        )
    </insert>

    <!-- 更新订单 -->
    <update id="updateOrderInfo" parameterType="com.gf.order.mapper.po.Order">
        UPDATE `gf-order` SET
        orderKey = #{orderKey},
        action = #{action}, actionTime = #{actionTime}
        WHERE groupID = #{groupID}
    </update>

</mapper>

6、启动类增加扫描mapper路径

@SpringBootApplication
@MapperScan(basePackages = "com.gf.order.mapper")
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}

7、建表语句

CREATE TABLE IF NOT EXISTS `gf-order`(
    `itemID`      bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
    `orderKey`    varchar(50) NOT NULL DEFAULT '' COMMENT '订单号',
	`groupID`     bigint(20) NOT NULL DEFAULT '0' COMMENT '集团ID',
    `actionTime` timestamp   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `createTime` timestamp   NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`itemID`)
) COMMENT='订单信息表';