如何使用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){
        ...
    }

    ...
    ...
    ...
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM