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

    ...
    ...
    ...
}
posted @ 2020-08-11 17:42  heaven096  阅读(874)  评论(0编辑  收藏  举报