0%
前言
SpringBoot整合Mybatis框架
在pom.xml添加依赖
1 2 3 4 5
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
|
SpringBoot配置
- 编辑
application.properties
配置文件
- 配置Mybatis的Mapper文件位置
1
| mybatis.mapper-locations=classpath:/mapper/*/*.xml
|
注解方式
Dao层定义接口
1 2 3 4 5 6 7 8 9
| @Mapper public interface GoodsDao {
@Delete("DELETE FROM tb_goods WHERE id=#{id}") public String deleteById(Integer id);
}
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @SpringBootTest public class GoodsDaoTests {
@Autowired private GoodsDao goodsDao; @Test public void testDeleteById() throws Exception { String row = goodsDao.deleteById(1); System.out.println("影响的行数:"+row); }
}
|
xml方式
定义Mapper文件
- 在
/src/main/resources/mapper/goods
新建Goods.Mapper.xml
SQL映射文件
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?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.cy.pj.goods.dao.GoodsDao"> <delete id="deleteObjects"> delete from tb_goods where id in <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach> </delete> </mapper>
|
配置Mapper文件
- 修改
application.properties
文件
1
| mybatis.mapper-locations=classpath:mapper/*/*.xml
|
Dao层定义接口
1 2 3 4
| @Mapper public interface GoodsDao { public Integer deleteObjects(@Param("ids")Integer... ids); }
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @SpringBootTest public class GoodsDaoTests {
@Autowired private GoodsDao goodsDao; @Test public void testDeleteObjects() throws Exception { int row = goodsDao.deleteObjects(2,4); System.out.println("影响的行数:"+row); }
}
|
完成