Spring Boot 整合 MyBatis

in TCEH with 0 comment

一、项目架构

20.png

二、在SpringBoot项目的.pom文件引入MyBatis及数据库相关

<!-- Springboot-mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>
<!--数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

三、源码

CityController.java

package com.back.mybatis.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.back.mybatis.model.City;
import com.back.mybatis.service.CityService;

@RequestMapping("/city")
@RestController
public class CityController {
    @Resource
    private CityService cityService;

    @GetMapping("list")
    public List<City> listCity() {
        return cityService.listCity();
    }
}

CityService.java

package com.back.mybatis.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.back.mybatis.mapper.CityMapper;
import com.back.mybatis.model.City;

@Service
public class CityService {
    @Autowired
    private CityMapper cityMapper;

    public List<City> listCity() {
        return (List<City>) cityMapper.selelctList();
    }

}

CityMapper.java

package com.back.mybatis.mapper;

import java.util.List;

import com.back.mybatis.model.City;

public interface CityMapper {

    List<City> selelctList();
}

City.java

package com.back.mybatis.model;

public class City {
    private Integer id;

    private String cityName;

    private String cityCode;

    public Integer getId() {
        return id;
    }

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

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName == null ? null : cityName.trim();
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode == null ? null : cityCode.trim();
    }
}

MyBatisApplication.java

package com.back.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.back.mybatis.mapper")//开启Mybatis扫描Dao
public class MyBatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBatisApplication.class, args);
    }

}

CityMapper.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.back.mybatis.mapper.CityMapper"> <!-- 命名空间映射至相应的Dao -->
    <resultMap id="BaseResultMap" type="com.back.mybatis.model.City"><!-- 表字段与模型字段映射 -->
        <id column="Id" jdbcType="INTEGER" property="id" />
        <result column="city_name" jdbcType="VARCHAR" property="cityName" />
        <result column="city_code" jdbcType="VARCHAR" property="cityCode" />
    </resultMap>

    <select id="selelctList" resultMap="BaseResultMap">
        select * from city
    </select>
</mapper>

application.properties

#模板页面资源
spring.thymeleaf.prefix=classpath:/templates/

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/network?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

#mapping文件位置。注意classpath:后面不要带空格!!!
mybatis.mapper-locations= classpath:mapping/*.xml
#模型类包
mybatis.type-aliases-package= com.back.mybatis.model

注意事项

1、mapping文件夹建在src/main/resources下。这样就不用再插件里配置mapping。
2、建议用MyBatis生成器,生成表对应的model、mapping、Dao。减少手工配置的失误。
附:生成器配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <classPathEntry  location="C:\Users\Back\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/network?serverTimezone=UTC" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.back.mybatis.model" targetProject="MyBatis/src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="MyBatis/src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.back.mybatis.mapper" targetProject="MyBatis/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="city" domainObjectName="City" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>
Comments are closed.