Mybatis讲解二

一.Mybatis的单表操作

1. 删除操作
1.1 Dao接口
//删除之参数是int类型
	public void deleteProductById(Integer id);
//删除之参数是实体类类型
	public void deleteProductByPojo(Product product)

1.2 Sql映射文件
<!-- 删除之主键删除id 
		注意:如果参数类型是基本数据类型,那么sql语句的参数名称可以随便起
	-->
	<delete id="deleteProductById" parameterType="int">
		delete from product where id=#{asfdsafasd}
	</delete>
	<!-- 删除之参数类型是pojo类
		注意:如果参数类型是pojo类类型,那么sql语句的参数名称不可以随便起,必须和当前实体类中的属性名称相对应
	-->
	<delete id="deleteProductByPojo" parameterType="product">
		delete from product where id=#{id}
	</delete>

1.3测试类
// 删除之参数类型是基本数据类型
   @Test
   public void demo4() {
   	session.getMapper(ProductMapper.class).deleteProductById(44);
   }
   // 删除之参数类型是pojo类型
   @Test
   public void demo5() {
   	Product product = new Product();
   	product.setId(24);
   	session.getMapper(ProductMapper.class).deleteProductByPojo(product);
   }

1.4 常见问题:
  • 如果当前sql映射文件中的参数名称不匹配实体类参数类型里的属性名称的话,则报一下异常。解决办法就是把sql语句的参数名称和实体类的属性名称一致。
2. 单一查询
2.1 dao接口
  //单一查询      
public Product selectProductByPrimarykey(Integer id);  
2.2 sql映射文件
<!-- 单一查询 
		parameterType表示参数类型,如果参数类型是基本数据类型的话,可以不用起别名直接使用
	-->
	<select id="selectProductByPrimarykey" parameterType="int" resultType="product">
		select 
			<include refid="basesql"/>
		from product where id=#{id}
	</select>

2.3 测试类
// 单一查询
		@Test
		public void demo6() {
			Product product = session.getMapper(ProductMapper.class).selectProductByPrimarykey(21);
			System.out.println(product);
		}

2.4 查询的常见问题
  • 注意:如果在查询的select标签中没有添加结果集属性,则会报以下异常,问题在于所有的查询的select标签中都必须加入结果集属性resultType或者resultMap。
3.模糊查询
3.1 dao接口
//模糊查询之普通类型
	public List selectProductBySearch(String name);
	//模糊查询之pojo
	public List selectProductBySearch1(Product product);
	//模糊查询之pojo2
	public List selectProductBySearch2(Product product);
	//模糊查询之map
	public List selectProductBySearch3(Map map);

3.2 sql映射文件
<!-- 1. 如果说参数类型是普通类型,那么在执行模糊查询的时候,只能使用#{}进行拼接查询 -->
	<select id="selectProductBySearch" parameterType="java.lang.String" resultType="products">
		select 
		 	<include refid="basesql"/>
		 from product 
		  where name like CONCAT(CONCAT('%',#{name},'%'))
	</select>
<!-- 2.模糊查询之模糊查询  之以${}形式
		参数必须是实体类类型,sql语句中参数名称不可以随意起,必须是实体类的属性名称	-->
	<select id="selectProductBySearch1" parameterType="products" resultType="products">
		select 
		 	<include refid="basesql"/>
		 from product 
		  where name like '%${name}%'
	</select>
	
<!-- 3.采用#{} -->
	<select id="selectProductBySearch2" parameterType="products" resultType="products">
		select 
		 	<include refid="basesql"/>
		 from product 
		  where name like "%"#{name}"%"
	</select>

<!--4.如果参数类型是map类型,那么sql语句中参数值一定是map集合中的key值 -->
	<select id="selectProductBySearch3" parameterType="map" resultType="products">
		select 
		 	<include refid="basesql"/>
		 from product 
		  where name like CONCAT(CONCAT('%',#{aaa},'%'))
	</select>

3.3 测试类
//模糊查询之普通类型
@Test
public void search2(){
	String name="p";
	List<Product>products =               	session.getMapper(ProductMapper.class).selectProductBySearch2(name);
		for (Product product : products) {
				System.out.println(product);
			}
		}		

@Test
public void search1(){
		Product product2=new Product();
		product2.setName("p");
		List<Product>products = session.getMapper(ProductMapper.class).selectProductBySearch(product2);
			for (Product product : products) {
				System.out.println(product);
			}
		}
@Test
public void search2(){
		Product product2=new Product();
		product2.setName("p");
		List<Product>products = session.getMapper(ProductMapper.class).selectProductBySearch4(product2);
			for (Product product : products) {
				System.out.println(product);
			}
		}
		
@Test
public void search3(){
	Map map=new HashMap<>();
	map.put("aaa", "p");
	List<Product>products = session.getMapper(ProductMapper.class).selectProductBySearch3(map);
		for (Product product : products) {
				System.out.println(product);
			}
		}

3.4 #{}和${}的区别
  • 要想打印sql语句,必须在sqlMapConfig.xml加入settings配置
<settings>
		<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>

  • 采用#{}形式赋值,采用是占位符形式?,防止sql注入攻击

  • 采用${}形式赋值,直接赋值,容易造成sql注入攻击

4. 分页查询
4.1 dao接口
//分页查询
   public List selectProductByPage(Map map);

4.2 sql映射文件
<!-- 分页查询 
   	注意:分页查询的时候参数类型必须是map类型,那么sql语句中limit后面的两个参数必须和map集合中的k值相对应
   -->
   <select id="selectProductByPage" parameterType="java.util.Map" resultType="product">
   	select 
   		<include refid="basesql"/>
   	from product  limit #{pageT},#{pageSize}
   </select>

4.3 测试类
// 分页查询
   @Test
   public void demo8() {
   	Map map=new HashMap();
   	map.put("pageT", 3);
   	map.put("pageSize", 3);
   	 List<Product>selectProductBySearch = session.getMapper(ProductMapper.class).selectProductByPage(map);
   	for (Product product2 : selectProductBySearch) {
   		System.out.println(product2);
   	}
   }

4.4 常见问题
  • 注意:如果使用两个参数的话,会报以下异常;加入分页查询的时候,参数不可以是多个参数类型,只能使用map类型,
5. 模糊分页查询
5.1 dao接口
//模糊分页查询
	public List selectProductBySearchAndPage(Map map);

5.2 sql映射文件
<!-- 动态分页查询 
		如果说参数类型是map类型,那么sql语句中的所有的参数名称必须和map集合中的k值相对应
	-->
	<select id="selectProductBySearchAndPage" parameterType="java.util.Map" resultType="product">
		select 
			<include refid="basesql"/>
		from product
		where  name like CONCAT(CONCAT('%',#{aname},'%'))
		 limit #{pageT},#{pageSize}
	</select>

5.3 测试类
// 动态分页查询
		@Test
		public void demo9() {
			Map map=new HashMap();
			map.put("aname", "冰");
			map.put("pageT", 2);
			map.put("pageSize", 1);
			 List<Product>selectProductBySearch = session.getMapper(ProductMapper.class).selectProductBySearchAndPage(map);

二. Mybatis的动态sql语句

1. if和trim(trim+if)
//选择性新增    
public void insertProductBySelecter(Product product);  
  • sql映射文件
<!-- 动态sql语句案例 
		if标签表示判断,如果符合条件,则执行条件内容
		trim表示去掉多余的指定的字符,prefix表示前缀,suffix表示后缀,suffixOverrides去除字段之后的指定字符
		prefixOverrides去除字段之前的指定字符
	-->
	<insert id="insertProductBySelecter" parameterType="product">
		insert into product
		<trim prefix="(" suffix=")" suffixOverrides="," >
			<if test="id!=null">
				id,
			</if>
			<if test="name!=null">
				name,
			</if>
			<if test="price!=null">
				price,
			</if>
			<if test="is_hot!=null">
				is_hot,
			</if>
			<if test="date!=null">
				date,
			</if>
			<if test="description!=null">
				description
			</if>
		</trim>
		values
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id!=null">
				#{id},
			</if>
			<if test="name!=null">
				#{name},
			</if>
			<if test="price!=null">
				#{price},
			</if>
			<if test="is_hot!=null">
				#{is_hot},
			</if>
			<if test="date!=null">
				#{date},
			</if>
			<if test="description!=null">
				#{description},
			</if>
		</trim>
	</insert>

  • 测试类
//动态sql语句if
		@Test
		public void demo10(){
			Product product = new Product();
			product.setName("fadsf");
	session.getMapper(ProductMapper.class).insertProductBySelecter(product);
		}

  • 对比观察 使用动态sql语句 控制台的输出
2. Choose (不建议使用)
//动态模糊查询1
public List selectProductBySearchdong(Product product);

<!-- choose
	不建议使用该标签
	当有一个when条件成立的时候则执行,那么之后的when条件不管成立与否均不在执行
	当所有的when条件都不成立的时候,则执行otherwise条件
-->
	<select id="selectProductBySearchdong" parameterType="product" resultType="product">
		select 
			<include refid="basesql"/>
		from product where 1=1
		<choose>
			<when test="price>0">
				and price=#{price}
			</when>
			<when test="name!=null">
				or name like '%${name}%'
			</when>
			<otherwise>
				and description=#{description}
			</otherwise>
		</choose>
	</select>


// 动态sql语句choose
	@Test
	public void demo11() {
		Product product = new Product();
		product.setPrice(6d);
		product.setName("冰");
		product.setDescription("fasgfnaninagi");
		List<Product>selectProductBySearchdong = session.getMapper(ProductMapper.class).selectProductBySearchdong(product);
		for (Product product2 : selectProductBySearchdong) {
			System.out.println(product2);
		}
	}

3.Where(where+if+trim)
  • sql映射文件
<!-- where+if 
		where标签表示条件连接符
		特性:如果一个条件成立,那么where标签会自动把and关键字去掉,
		若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
		如果所有条件都不成立,那么where会启动自毁程序,把自己干死
	-->
	<!--List<Pet> selectActive(Map map);-->
1.trim 和 if  
    <select id="selectActive" parameterType="map" resultType="pet">

        <!--
        where 没有属性
        1.可以自动去除第一个 and
        2.如果一个条件都没有  where 自己也消失
        -->
        select * from pet
        <trim prefix="where" prefixOverrides="and || where " suffix="limit #{start},#{size}">
            <if test="name!=null">
               and name like "%"#{name}"%"
            </if>
            <if test="breed!=null">
                and breed=#{breed}
            </if>
            <if test="sex!=null">
                and sex=#{sex}
            </if>
            <if test="startBirth!=null">
                and birth &gt;= #{startBirth}
            </if>
            <if test="endBirth!=null">
                and birth &lt;= #{endBirth}
            </if>
        </trim>
        
2.where 和 if         
        
        
        <!--List<Pet> selectActive(Map map);-->
    <select id="selectActive" parameterType="map" resultType="pet">

        <!--
        where 没有属性
        1.可以自动去除第一个 and
        2.如果一个条件都没有  where 自己也消失
        -->
        select * from pet
        <where>
            <if test="name!=null">
               and name like "%"#{name}"%"
            </if>
            <if test="breed!=null">
                and breed=#{breed}
            </if>
            <if test="sex!=null">
                and sex=#{sex}
            </if>
            <if test="startBirth!=null">
                and birth &gt;= #{startBirth}
            </if>
            <if test="endBirth!=null">
                and birth &lt;= #{endBirth}
            </if>
        </where>
        limit #{start},#{size}
    </select>

4.Set 修改(set+if+trim)
//选择性修改
	public void updateProductBySelecter(Product product);

  • sql映射文件
<!-- 选择性修改
	set标签专用于修改,特性就是会自动去除掉最后一个条件的之后的逗号
	-->
	<update id="updateProductBySelective" parameterType="products">
		update product 
			<!-- <set>
				<if test="name!=null">
					name=#{name},
				</if>
				<if test="price!=null">
					price=#{price},
				</if>
				<if test="date!=null">
					date=#{date},
				</if>
				<if test="is_hot!=null">
					is_hot=#{is_hot},
				</if>
				<if test="description!=null">
					description=#{description},
				</if>
			</set> -->
			<trim prefix="set" suffixOverrides=",">
				<if test="name!=null">
					name=#{name},
				</if>
				<if test="price!=null">
					price=#{price},
				</if>
				<if test="date!=null">
					date=#{date},
				</if>
				<if test="is_hot!=null">
					is_hot=#{is_hot},
				</if>
				<if test="description!=null">
					description=#{description},
				</if>
			</trim>
			<where>
					id=#{id}
			</where>
	</update>

  • 测试类
//动态set
	@Test
	public void demo12(){
		Product product = session.getMapper(ProductMapper.class).selectProductByPrimarykey(46);
		product.setName("张学友");
		session.getMapper(ProductMapper.class).updateProductBySelecter(product);
	}

5.Foreach 批量
  • 注意:使用foreach,接口的参数类型有两种,第一种是list类型,第二种是数组array类型
1.批量查询(参数类型是list)
  • Dao接口
//批量查询
	public List selectProdcutByForeach(List pList);

  • Sql映射文件
<!-- foreach批量查询 
		foreach标签表示循环标签,collection表示集合属性,属性值有两种,
		如果接口的参数是List类型,那么该属性值=list
		如果接口的参数是数组类型,那么该属性值=array
		open属性表示类似于前缀
		close表示类似于后缀
		item表示集合的遍历体,属性值随意起
		separator表示隔离间隔的关键字属性,
		sql:SELECT * FROM product WHERE id IN(47,46,1,10)
		foreach标签之间展示的每次遍历的id值,表达形式#{item属性值}
	-->
	<select id="selectProdcutByForeach" parameterType="java.util.List" resultType="product">
		select 
			<include refid="basesql"/>
		from product 
		<where>
			id in 
			<foreach collection="list" open="(" item="aid" separator="," close=")">
				#{aid}
			</foreach>
		</where>
	</select>

  • 测试类
//动态foreach
		@Test
		public void demo13(){
			List pList=new ArrayList<>();
			pList.add(46);
			pList.add(47);
			pList.add(48);
			List<Product>selectProdcutByForeach = session.getMapper(ProductMapper.class).selectProdcutByForeach(pList);
			for (Product product2 : selectProdcutByForeach) {
				System.out.println(product2);
			}

2.批量删除(参数类型是数组类型)
  • Dao接口
//批量删除
   public void deleteProudctByForeach(Integer[] ids);

  • Sql映射文件
<!-- foreach批量删除 -->
	<delete id="deleteProudctByForeach" parameterType="Integer[]">
		delete from product 
			<where>
				id in
				<foreach collection="array" open="(" item="aid" separator="," close=")">
					#{aid}
				</foreach>
			</where>
	</delete>

  • 测试类
// 动态foreach2
	@Test
	public void demo14() {
		Integer [] ids={46,47,48};
		session.getMapper(ProductMapper.class).deleteProudctByForeach(ids);
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值