如何使用SpringBoot整合Mybatis——注解方式

一、介绍

SpringBoot有两种方法来整合Mybatis,一种是XML文件配置方式,另一种是注解方式,主要优势点如下:

  • XML配置方式:隔离sql和业务代码,能够更为清晰地表达sql,尤其是对于较长的sql代码;
  • 注解方式:代码更为精简,方便。

本文主要讨论如何用注解方式来整合Mybatis。

二、实现

新建SpringBoot项目

新建一个SpringBoot项目,这个很简单,这里不再赘述。

导入相关依赖

由于要整合Mybatis,所有我们需要在项目的配置文件pom.xml中添加mysql和mybatis依赖:

<!--mysql依赖-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

准备数据库

  1. 数据库的创建
    准备一个测试用的product_Category表,其中有category_idcategory_namecategory_type三个属性,其中category_id为主键且自增,然后可以插入一些数据。
CREATE TABLE `product_category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(64) NOT NULL COMMENT '类目名字',
  `category_type` int(11) NOT NULL COMMENT '类目编号',
  PRIMARY KEY (`category_id`),
  UNIQUE KEY `uqe_category_type` (`category_type`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COMMENT='类目表';

INSERT INTO product_category values (1,"热销榜",2);
INSERT INTO product_category values (2,"热评榜",1);


2. 在项目配置文件application.yml中配置数据源:

# 数据库配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://10.3.11.185/sell?characterEncoding=utf-8&useSSL=false

新建实体类层

根据数据库创建实体类。为了精简代码,后面大多使用了Lombok插件,比如使用@Data注解,需要事先下载Lombok插件,然后在pom.xml引入依赖:

<!--导入Lombok依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

//productCategory实体类
@Entity
@Data
public class ProductCategory {
    //类目id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增
    private Integer categoryId;

    //类目名字
    private String categoryName;

    //类目编号
    private Integer categoryType;
}

编写实体类对应接口,在这里就可以直接使用注解写sql语句了

这里模拟使用mybatis对类目进行增删改查:

public interface ProductCategoryMapper {

    //方法一:以Map的方式插入(注意values中的写法,要指定数据类型)
    @Insert("insert into product_category(category_name,category_type) values (#{category_name,jdbcType=VARCHAR},#{category_type,jdbcType=INTEGER})")
    int insertByMap(Map<String,Object> map);

    //方法二:以对象的方式插入
    @Insert("insert into product_category(category_name,category_type) values (#{categoryName,jdbcType=VARCHAR},#{categoryType,jdbcType=INTEGER})")
    int insertByObject(Object object);

    @Select("select * from product_category where category_type = #{categoryType}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType"),
    })
    ProductCategory findByCategoryType(Integer categoryType);

    @Select("select * from product_category where category_name = #{categoryName}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType"),
    })
    List<ProductCategory> findByCategoryName(String categoryName);

    @Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")
    int updateByCategoryType(@Param("categoryName") String categoryName, @Param("categoryType") Integer categoryType);

    //根据一个对象去更新
    @Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}")
    int updateByObject(Object object);

    @Delete("delete from product_category where category_type = #{categoryType}")
    int deleteByCategoryType(Integer categoryType);

}

配置Mapper扫描的路径

要想程序正常运行,还需要让程序知道Mapper文件的位置,需要配置Mapper扫描的路径。在启动的主类上添加@MapperScan注解,basePackages属性值即为刚才写的实体类对应接口的路径:

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.dataobject.mapper")
public class SellApplication {
    public static void main(String[] args) {
        SpringApplication.run(SellApplication.class, args);
    }
}

对实体类对应接口进行单元测试:

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

    @Autowired
    private ProductCategoryMapper mapper;

    @Test
    public void insertByMap() throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("category_name","可口可乐");
        map.put("category_type",12);
        int result = mapper.insertByMap(map);
        Assert.assertEquals(1,result);
    }

    @Test
    public void insertByObject() throws Exception{
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryName("雪碧");
        productCategory.setCategoryType(14);
        int result = mapper.insertByObject(productCategory);
        Assert.assertEquals(1,result);
    }

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

    @Test
    public void findByCategoryName(){
        List<ProductCategory> result = mapper.findByCategoryName("雪碧");
        Assert.assertNotEquals(0,result.size());
    }

    @Test
    public void updateByCategoryType(){
        int result = mapper.updateByCategoryType("雪小碧",14);
        Assert.assertEquals(1,result);
    }

    @Test
    public void updateByObject(){
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryName("芬达");
        productCategory.setCategoryType(14);
        int result = mapper.updateByObject(productCategory);
        Assert.assertEquals(1,result);
    }

    @Test
    public void deleteByCategoryType(){
        int result = mapper.deleteByCategoryType(14);
        Assert.assertEquals(1,result);
    }
}

可以发现数据库中的数据被更新了:

再对应写Service层代码

Service接口:

public interface CategoryService {

    int insertByMap(Map<String,Object> map);

    ProductCategory findByCategoryType(Integer categoryType);

    List<ProductCategory> findByCategoryName(String categoryName);

    int updateByCategoryType(String categoryName,Integer categoryType);
    
    int deleteByCategoryType(Integer categoryType);
}

Service接口实现类CategoryServiceImpl:

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

 
    @Override
    int insertByMap(Map<String,Object> map){
        return mapper.insertByMap(map);
    }

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

    ...
    ...
    ...
}

9. 对应写Controller层代码

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

    @Autowired
    private CategoryService categoryService;

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

    ...
    ...
    ...
}
原文地址:https://www.cnblogs.com/xiaozhengtongxue/p/13476577.html