spring boot 整合mybatis

导入mybatis jar包
右键pom.xml


模拟springboot底层实现类
1.
定义接口

@Mapper

public interface GoodsDao {
	/**
	 * 基于商品id删除商品
	 * @param id 商品id
	 * @return 删除行数
	 * 数据层方法对象的sql映射
	 */

         @Delete("delete from tb_goods where id=#{id}")
            //当传入的参数只有一个且不是数组时
            //#{id}这个地方的变量可以不是传入的参数名(自己随意)
         int deleteById(Integer id);

}

测试

@SpringBootTest
public class TestGoods {

	@Autowired
	private GoodsDao gd;
	@Test
	void TestGoods() {
		int i =gd.deleteById(10);
		System.out.println(i);
	}
}

2.
自己实现

接口方法

@Mapper

public interface GoodsDao {
	/**
	 * 基于商品id删除商品
	 * @param id 商品id
	 * @return 删除行数
	 * 数据层方法对象的sql映射
	 */

         @Delete("delete from tb_goods where id=#{id}")

         int deleteById(Integer id);

}
@Component
public class GoodsDaoImpl {

	@Autowired
	private SqlSession sqlSession;
	 
	public int deleteById(Integer id) {
		return  sqlSession.delete("com.cy.demo.goods.dao.GoodsDao.deleteById", id);
		//sqlSession.delete("com.cy.demo.goods.dao.deleteById",id)
	}
}

@SpringBootTest
public class GoodsDaoImpTest {

	@Autowired
	private GoodsDaoImpl gdi;
	@Test
	void testdelete() {
		int i = gdi.deleteById(9);
		
		System.out.println(i);
	}	
}

直接导mapper文件找对应的元素
3.
当sql语句比较复杂时使用映射文件

接口:

 /**
            *GoodsDao.java
          * ids可以接受多个参数
            * 在mapper文件中直接使用array来接受,
          * @param ids
          * @return
          */
         int deleteObject(/*@Param("ids")*/Integer...ids);
            //当mybatis过低时需要加上@Param("ids")才能识别

不加@Param("ids")报错

使用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.cy.demo.goods.dao.GoodsDao">
	<delete id="deleteObject">
		delete from tb_goods
		<where>
			
			<if test="ids!=null and ids.length>0">
			id in
				<foreach collection="ids" open="(" close=")" separator=","
					item="i">
					#{i}
				</foreach>
			</if>
			or 1=2
		</where>

	</delete>
</mapper>

配置:

测试:

	@Autowired
	private GoodsDao gd;
	
	@Test
	void deleteObject() {
		int rows=gd.deleteObject(1,2,3);
		System.out.println(row);
	}

当我们在执行此方法时,其实现类内部会检测接口方法上是否有定义sql映射
假如没有,然后基于接口类全名找到对应的映射文件(mapper映射文件的id),然后在基于方法名
再找到对应映射文件的元素,进而获取sql映射

错误解决:



binding异常还有可能时参数异常,还有可能是配置文件有问题

posted @ 2020-08-01 14:15  岁月染过的梦  阅读(148)  评论(0)    收藏  举报