spring-boot 框架整合 MyBatis

本文討論使用 mybatis-spring-boot-starter 的方式整合進 spring-boot 框架中

本文也只詳細討論基於 xml 的配置,基於註解的方式比 xml 要簡單,再也不作詳細講解。html

一、將 MyBatis 加入 pom.xml 配置

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

二、application.yml 配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/用哪一個數據庫?useUnicode=true&characterEncoding=utf-8
    username: 用戶名
    password: 密碼

server:
  port: 8080

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

MyBatis 配置項解讀:java

  • config-location:指定 MyBatis 主配置文件的位置
  • mapper-locations:指定 mapper 文件的位置。若是在項目中你的 mapper 文件是按目錄來放置,那麼對應的配置就變成:mapper-locations: classpath:mapper/*/*.xml

這時候假設咱們的 resources 結構是這樣的:mysql

|-resources
|--config
|---application.yml
|---mybatis-config.xml
|--mapper
|---CityMapper.xml

三、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>
    <typeAliases>
        <package name="com.mybatis.domain"/>
    </typeAliases>
    <!--<mappers>-->
        <!--<mapper resource="sample/mybatis/mapper/CityMapper.xml"/>-->
        <!--<mapper resource="sample/mybatis/mapper/HotelMapper.xml"/>-->
    <!--</mappers>-->
</configuration>

這個配置見仁見智,在它裏面我就配置了一個 typeAliases。不瞭解的同窗能夠移步文檔查看相關解釋。git

你也能夠把 mapper 配置在此處,有多少個 mapper 就配置多少次,固然,咱們已經在 application.yml中批量指定了,很方便,就不用在此處一個個寫。github

四、接下來就是業務代碼部分了

假設咱們的目錄結構是這樣的:spring

|-com.mybatis
|--controller
|---CityRestController.java (控制器)
|--domain
|---City.java (實體類)
|--mapper
|---CityMapper.java (mybatis的mapper)
|--service
|---CityService.java (service 接口)
|---CityServiceImpl.java (service 實現)
|--MyApplication.java (入口)

首先咱們定義城市這個實體類:sql

public class City implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;

    private Long provinceId;

    private String cityName;

    public Long getId() {
        return id;
    }

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

    public Long getProvinceId() {
        return provinceId;
    }

    public void setProvinceId(Long provinceId) {
        this.provinceId = provinceId;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    @Override
    public String toString() {
        return "City{" +
                "id=" + id +
                ", provinceId=" + provinceId +
                ", cityName='" + cityName + '\'' +
               '}';
    }
}

接着咱們來定義mapper:數據庫

//@Mapper
public interface CityMapper {

    City findByProvinceId(Long provinceId);

    List<City> findAll();
}

定義這個 mapper 的做用是用來跟數據庫進行交互的。api

請注意,這裏我把 @Mapper註解給註釋掉了,你們先把這個註釋打開,待會再來解釋。mybatis

另外,若是你想使用註解的方式來操做數據庫,那麼能夠這樣來定義 mapper:

//@Mapper
public interface CityMapper {
    @Select("select * from city where province_id = #{provinceId}")
    // 返回結果實體屬性與數據庫字段轉換
    @Results({
            @Result(property = "provinceId", column = "province_id"),
            @Result(property = "cityName", column = "city_name")
    })
    City findByProvinceId(@Param("provinceId") Long provinceId);
}

對於選擇使用註解仍是使用 xml 的方式,你們能夠靈活選擇,好比簡單的語句可使用註解,複雜的語句使用 xml,固然,仍是須要跟團隊保持一致。

還記得咱們 resources 的結構嗎?

裏面有一個mapper目錄,咱們配置了在這個目錄裏面尋找 mapper 文件。

這裏我定義了一個 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.mybatis.mapper.CityMapper">
    <resultMap id="BaseResultMap" type="com.mybatis.domain.City" >
        <result column="province_id" property="provinceId" />
        <result column="city_name" property="cityName" />
    </resultMap>
    <select id="findByProvinceId" resultMap="BaseResultMap">
        select * from city where province_id = #{provinceId}
    </select>
    <select id="findAll" resultMap="BaseResultMap">
        select * from city
    </select>
</mapper>

文件解讀:

  • namespace 屬性用於跟我們業務中的那個 mapper 進行關聯
  • resultMap 標籤用來定義字段映射和結果字段返回類型
  • select 中的 id 屬性用來跟我們業中 mapper 的方法進行關聯,查詢到的結果就會返回給該方法
  • #{}是佔位符,表示須要動態獲取的數據

最後定義 service 來處理我們的業務:

public interface CityService {

    City getByProvinceId(Long provinceId);

    List<City> getAll();

}
@Service
public class CityServiceImpl implements CityService {

    @Resource
    private CityMapper cityMapper;

    @Override
    public City getByProvinceId(Long provinceId) {
        return cityMapper.findByProvinceId(provinceId);
    }

    @Override
    public List<City> getAll() {
        return cityMapper.findAll();
    }
}

在controller裏面進行驗證:

@RestController
@RequestMapping("/api")
public class CityRestController {

    @Resource
    private CityService cityService;

    @GetMapping("/cities")
    public List<City> cities () {
        return cityService.getAll();
    }

    @GetMapping("/city/{provinceId}")
    public City city(@PathVariable long provinceId) {
        return cityService.getByProvinceId(provinceId);
    }

}

最後

還記得我定義CityMapper.java的時候,爲何把@Mapper給註釋掉了嗎?是由於我在入口文件這裏定義了到哪裏去找 mapper 文件,因此就不用再在每一個 mapper 文件中再寫個註解了:

@SpringBootApplication
@MapperScan("com.mybatis.mapper") // 定義了在哪裏掃描mapper文件
public class MyApplication {

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

至此,spring-boot 與 mybatis 整合完畢。

五、附上三個 MyBatis 連接,分別是:

一、mybatis-spring-boot-starter 配置項手冊

二、GitHub倉庫地址,包含代碼示例

三、中文官方文檔

相關文章
相關標籤/搜索