1. 程式人生 > >30 SpringBoot與Mybatis整合

30 SpringBoot與Mybatis整合

1 準備

1.1 引入依賴

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

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</
artifactId
>
<scope>runtime</scope> </dependency> <!--引入druid資料來源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency>

1.2 用到的sql


/*
Navicat MySQL Data Transfer

Source Server         : Localhost:3306
Source Server Version : 50622
Source Host           : localhost:3306
Source Database       : mall

Target Server Type    : MYSQL
Target Server Version : 50622
File Encoding         : 65001

Date: 2018-12-10 15:29:06
*/
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `m_cart` -- ---------------------------- DROP TABLE IF EXISTS `m_cart`; CREATE TABLE `m_cart` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID', `user_id` bigint(20) DEFAULT NULL COMMENT '使用者ID', `item_id` bigint
(20) DEFAULT NULL COMMENT '商品ID', `item_title` varchar(100) DEFAULT NULL COMMENT '商品標題', `item_image` varchar(500) DEFAULT NULL COMMENT '商品主圖', `item_price` bigint(20) DEFAULT NULL COMMENT '商品價格,單位為:分', `num` int(10) DEFAULT NULL COMMENT '購買數量', `create_time` bigint(14) DEFAULT NULL, `update_time` bigint(14) DEFAULT NULL, PRIMARY KEY (`id`), KEY `userId_itemId` (`user_id`,`item_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='購物車模組'; -- ---------------------------- -- Records of m_cart -- ---------------------------- /* Navicat MySQL Data Transfer Source Server : Localhost:3306 Source Server Version : 50622 Source Host : localhost:3306 Source Database : mall Target Server Type : MYSQL Target Server Version : 50622 File Encoding : 65001 Date: 2018-12-11 10:37:58 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `m_item_param_template` -- ---------------------------- DROP TABLE IF EXISTS `m_item_param_template`; CREATE TABLE `m_item_param_template` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `cat_id` bigint(20) NOT NULL COMMENT '商品類目ID', `param_data` text NOT NULL COMMENT '引數資料,格式為json格式', `create_time` bigint(14) NOT NULL COMMENT '建立時間', `update_time` bigint(14) NOT NULL COMMENT '修改時間', PRIMARY KEY (`id`), KEY `item_cat_id` (`cat_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='商品規則引數模板'; -- ---------------------------- -- Records of m_item_param_template -- ---------------------------- INSERT INTO `m_item_param_template` VALUES ('1', '3', '[\n {\n \"group\": \"主體修改\",\n \"params\": [\n \"品牌\",\n \"型號修改\",\n \"入網型號修改\",\n \"上市年份修改\"\n ]\n },\n {\n \"group\": \"基本資訊\",\n \"params\": [\n \"機身顏色\",\n \"機身長度(mm)\",\n \"機身寬度(mm)\"\n ]\n }\n ]', '20180927173853', '20180927173853');

2 註解版使用Mybatis

2.1 簡單測試

  • CartMapper
package com.gp6.springboot25.mapper;

import com.gp6.springboot25.bean.Cart;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface CartMapper {
    @Select("select * from m_cart where id = #{id}")
    public Cart selectCartById(int id);
}

  • CartController
package com.gp6.springboot25.controller;

import com.gp6.springboot25.bean.Cart;
import com.gp6.springboot25.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CartController {
    @Autowired
    CartMapper cartMapper;

    @GetMapping("/cart/{id}")
    public Cart selectCartById(@PathVariable("id") Integer id) {
        return cartMapper.selectCartById(id);
    }
}

2.2 http://localhost:8080/cart/1

測試結結果

  • 未開啟駝峰對映,userId與資料庫中user_id不能對應

2.3 開啟駝峰對映規則

package com.gp6.springboot25.config;


import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {

            @Override
            public void customize(Configuration configuration) {
                // 開啟駝峰命名法對映規則
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

  • 詳見org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

3 配置版使用Mybatis

3.1 新增配置檔案

<?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>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

3.2 ItemParamTemplateMapper

package com.gp6.springboot25.mapper;

import com.gp6.springboot25.bean.ItemParamTemplate;

public interface ItemParamTemplateMapper {
    ItemParamTemplate selectItemParamTemplateById(int id);
}

3.3 ItemParamTemplateController

package com.gp6.springboot25.controller;

import com.gp6.springboot25.bean.ItemParamTemplate;
import com.gp6.springboot25.mapper.ItemParamTemplateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ItemParamTemplateController {

    @Autowired
    ItemParamTemplateMapper itemParamTemplateMapper;

    @GetMapping("/itemParamTemplate/{id}")
    public ItemParamTemplate selectCartById(@PathVariable("id") Integer id) {
        return itemParamTemplateMapper.selectItemParamTemplateById(id);
    }
}

3.4 ItemParamTemplateMapper.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.gp6.springboot25.mapper.ItemParamTemplateMapper">

    <resultMap id="BaseResultMap" type="com.gp6.springboot25.bean.ItemParamTemplate">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="cat_id" property="catId" jdbcType="BIGINT"/>
    </resultMap>

    <resultMap id="ResultMapWithBLOBs" type="com.gp6.springboot25.bean.ItemParamTemplate" extends="BaseResultMap">
        <result column="param_data" property="paramData" jdbcType="LONGVARCHAR"/>
    </resultMap>


    <select id="selectItemParamTemplateById" resultType="com.gp6.springboot25.bean.ItemParamTemplate">
        SELECT * FROM m_item_param_template WHERE id=#{id}
    </select>
</mapper>

3.5 application

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