1. 程式人生 > 實用技巧 >如何使用SpringBoot整合Mybatis——XML配置方式

如何使用SpringBoot整合Mybatis——XML配置方式

一、介紹

SpringBoot有兩種方法來整合Mybatis,一種是XML檔案配置方式,另一種是註解方式,主要優勢點如下:

  • XML配置方式:隔離sql和業務程式碼,能夠更為清晰地表達sql,尤其是對於較長的sql程式碼;
  • 註解方式:程式碼更為精簡,方便。

上一篇隨筆中講述瞭如何用註解方式來整合Mybatis,雖然簡單省事,但是全註解的方式對於動態sql語言的支援實在是不太友好,本文主要討論如何用XML配置的方式來整合Mybatis。

二、實現

本文采用的資料庫和實體類均與上一篇文章一致,因此這裡只講述XML檔案的配置方法。

在上文中的實體類對應介面先宣告方法

public interface ProductCategoryMapper {

    //1.先進行方法的宣告
    ProductCategory selectByCategoryType(Integer categoryType);
}

在resources目錄下新建xml配置檔案

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.imooc.dataobject.mapper.ProductCategoryMapper">  <!--填寫對映當前的Mapper介面,所有的增刪改查的引數和返回值型別,
		就可以直接填寫縮寫,不區分大小寫,直接通過方法名去找型別-->
    <!--要返回的結果,type就是資料庫對應的物件-->
    <resultMap id="BaseResultMap" type="com.imooc.dataobject.ProductCategory">
        <id column="category_id" property="categoryId" jdbcType="INTEGER" />
        <id column="category_name" property="categoryName" jdbcType="VARCHAR" />       <!--property即為實體類的欄位名,不要忘記jdbcType-->
        <id column="category_type" property="categoryType" jdbcType="INTEGER" />
    </resultMap>

    <!--sql語句-->
    <select id="selectByCategoryType" resultMap="BaseResultMap" parameterType="java.lang.Integer">                 <!--id即為前面宣告的方法名,parameterType是要傳入的引數的資料型別-->
        select category_id,category_name,category_type
        from product_category
        where category_type = #{category_type,jdbcType=INTEGER}
    </select>
</mapper>

pom.xml檔案中配置xml檔案路徑

要讓專案能找到xml檔案,則應該在專案配置檔案pom.xml中配置路徑:

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

對宣告的方法進行單元測試

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
class ProductCategoryMapperTest {

    @Autowired
    private ProductCategoryMapper mapper;

    @Test
    public void selectByCategoryType(){
        ProductCategory result = mapper.selectByCategoryType(13);
        Assert.assertNotNull(result);
    }
}


結果正確。

再對應寫Service層程式碼

Service介面:

public interface CategoryService {

    ProductCategory selectByCategoryType(Integer categoryType);
}

Service介面實現類CategoryServiceImpl:

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private ProductCategoryMapper mapper;

 
    @Override
    ProductCategory selectByCategoryType(Integer categoryType){
        return mapper.selectByCategoryType(categoryType);
    }

}

對應寫Controller層程式碼

@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    // 類目列表
    @GetMapping("/list")
    public ProductCategory selectByCategoryType(@RequestParam(value = "categoryType") Integer categoryType){
        ...
    }

    ...
    ...
    ...
}