第十八天(2024.8.6)Mybatis 动态注入

1.在common包下创建一个CommonResult类

这个类用来记录返回值,规范返回值格式。

int类型的code用来记录访问网页时的错误类型,String类型的message用来记录成功与否,Object类的data属性用来存储传入的对象。

在此类中写各种含参的方法,在成功时调用成功的方法,或特殊情况下调用失败的方法

package com.easy.common;

import java.io.Serializable;

public class CommonResult implements Serializable{
    private int code; 
    private String message;
    private Object data;

    public CommonResult(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static CommonResult success(int code, String message, Object data) {
        return new CommonResult(code, message, data);
    }
    public static CommonResult success(int code, String message) {
        return new CommonResult(code, message, null);
    }
    public static CommonResult success(Object data) {
        return new CommonResult(200, "操作成功", data);
    }
    public static CommonResult success() {
        return new CommonResult(200, "操作成功", null);
    }

    public static CommonResult fail(int code, String message, Object data) {
        return new CommonResult(code, message, data);
    }
    public static CommonResult fail(int code, String message) {
        return new CommonResult(code, message, null);
    }
    public static CommonResult fail(){
        return new CommonResult(400,"操作失败",null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

2.动态查询

Mybatis中提供了许多标签,简化了SQL语句。根据参数不同,可以组合出不同的SQL语句      

1.Mybatis模糊查询操作

        昨天写的查询语句是查询的department表,输入id查询出code和name,并且查询出来的是单行数据。查询出来的结果中的每一行,都要映射成该类型的对象,所以查询多行数据时要使用集合类。

在Staff表的映射文件中:

Mybatis提供了各种标签,可以通过<where></where>标签来限定查询条件,也有<if>标签来限定参数的条件,这里传入一个参数checktext,如果checktext不为null(未在apipose中写入参数名称)或为空(在apipose中写入参数类型为checktext,但是为传入值),参数就会执行<if>标签内部的操作。<bind>标签是重新定义一个参数,修改原来参数的内容(原来的参数不会改变,这里需要用一个新的参数liketext来记录参数模糊查询的形式,即%checktext%)

<select id="getStaff" resultType="com.easy.bean.Staff">
	select * from staff
	<!-- 根据参数不同,组合出不同的SQL语句      动态SQL语句     标签 -->
	<where>
		<!-- 这里编写条件语句    如果where标签中有内容    会自动添加where关键字 -->
		<if test="checktext !=null and checktext !='' ">
			<!-- 重新定义参数内容,这里为了给模糊查询加上% -->
			<bind name="liketext" value="'%'+checktext+'%'"/>
			name like #{liketext}
		</if>
	</where>
</select>

在dao包下的接口中写入方法getStaff():

package com.easy.dao;

import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.easy.bean.Staff;

@Mapper
public interface IStaffDao {
	List<Staff> getStaff(String checktext);
}

在Controller类中写入:

创建集合类对象list来存储dao.Staff(checktext)的返回集合,然后返回类型为CommonResult的,调用CommonResult.success方法,将list传入。

	@GetMapping("staff")
	public CommonResult getStaff(String checktext) {
		List<Staff> list=dao.getStaff(checktext);
		return CommonResult.success(list);
	}

运行起启动类后,在apipose中执行模糊查询,传入参数checktext为吹,查询结果为:

可以查询出name中包含'吹'的元素的数据

2.条件判断查询

        传入一个参数(低,中,高),每一个参数对应着一个工资范围,输入参数时会查询出工资在这个范围的表中元素

映射文件:首先通过where标签限定查询的条件,在choose标签中写when标签,一个when标签对应着一个参数值,匹配到这个参数时就执行相应的SQL语句。

注意:

小于:&lt;                               小于等于&lt;=

大于:&gt;                              大于等于&gt;=

<select id="getStaffBySalary" resultType="com.easy.bean.Staff">
	select * from staff
	<where>
	<!-- 参数名   salarytext -->
	<choose>
		<when test='salarytext=="低"'>
			salary &lt;= 5000
		</when>
		<when test='salarytext=="中"'>
			salary &gt; 5000 and salary &lt;= 8000
		</when>
		<otherwise>
			salary &gt; 8000
		</otherwise>
	</choose>
	</where>
</select>

dao包下接口中语句:

查询多条语句要用集合来存储(因为每条信息对应着一个对象)

List<Staff> getStaffBySalary(String salarytext);

Controller中:

    @GetMapping("staff/salary")
	public CommonResult getStaffBySalary(String salarytext) {
		List<Staff> list =dao.getStaffBySalary(salarytext);
		return CommonResult.success(list);
	}

执行查询后查出工资水平为中(5000~8000]的元素

3.映射查询 

1.一对一关系查询

现在有员工表Staff和部门表Department,查询每个员工时同时查询出该员工对应的部门信息,就是一种 一对一关系

这里select * from staff的返回类型并没有写resultType,而是写的resultMap。resultMap是一种映射关系,我们可以写一个resultMap标签,其中指明映射的类型,以及需要进行的子查询。

<!-- 一对一查询或一对多查询需要指定映射方式     resultMap-->
<resultMap id="staffAndDep" type="com.easy.bean.Staff">
	<association  column="dep_id" select="getStaffDep" property="dep"></association>
</resultMap>
<select id="getStaffDep" resultType="com.easy.bean.Department">
	select * from department where id=#{id}
</select>
<select id="getStaffAndDep" resultMap="staffAndDep">
	select * from staff
</select>

2.一对多查询

查询部门表时,同时将该部门中拥有的各员工信息同时查询出来,是一种一对多的关系。在这种一对多的映射关系下,同样也需要子查询

<!-- 部门表一对多查询 -->
<resultMap id="departmentAndStaff" type="com.easy.bean.Department"  >
	<!-- <id column="id" property="depid"></id>
	<result column="name" property="depname"></result> -->
	<result column="id" property="id"></result>
	<collection fetchType="lazy" column="id" select="getDepStaff" property="staffList"></collection>
</resultMap>
<select id="getDepStaff" resultType="com.easy.bean.Staff">
	select * from staff where dep_id=#{id}
</select>

<select id="getDep" resultMap="departmentAndStaff">
	select * from department
</select>

4.循环遍历插入

在staff的映射文件中写插入的SQL语句

<insert id="addList">
	insert into staff(code,name,salary,username,userpass) 
	values
	<foreach collection="list" item="it" separator=",">
	(#{it.code},#{it.name},#{it.salary},#{it.username},#{it.userpass})
	</foreach>
</insert>

controller中
 

@PostMapping("staff")
	public String addStaff(Staff staff) {
		staff=new Staff();
		staff.setCode("10001");
		staff.setName("吹杨");
		staff.setSalary(new BigDecimal(2000));
		staff.setUsername("chui yang");
		staff.setUserpass("123456");		
		List list=new ArrayList();
		list.add(staff);
		
		staff=new Staff();
		staff.setCode("10011");
		staff.setName("凯瑞");
		staff.setSalary(new BigDecimal(2000));
		staff.setUsername("kyrie");
		staff.setUserpass("123456");
		list.add(staff);
		
		dao.addList(list);
		return "成功";
	}

dao包下的接口中写:

int addList(List<Staff> list);

最终实现了添加操作,id=11 id=12就是添加进去的数值

5. 修改表元素的指定列数据(任意列)

staff表的映射文件中:

通过Mybatis提供的set,if标签,判断传入的name和salary是否为空/null,然后对这一列的数据进行修改。

<update id="editStaffItem">
	update staff
	<set>
		<if test='name!=null and name!=""'>
			name=#{name},
		</if>
		<if test="salary!=null">
			salary=#{salary},
		</if>
	</set>
	<where>
		id=#{id}
	</where>
</update>

接口中:

int editStaffItem(Staff staff);

Controller中:

    @PutMapping("staff")
	public String editStaff(Staff staff) {
		dao.editStaff(staff);
		return "success!!";
	}

修改id=1的数据:

3.缓存 

1.一级缓存

在查询一次后,第二次查询会直接返回第一次查询后的数据,这就是一级缓存

使用“--------”可以检测出两个查询是否执行

    @GetMapping("dep")
   	@Transactional//事务的注解,加上之后会使用一级缓存
	public CommonResult getDep() {
		List<Department> list=dao.getDep();
		System.out.println("--------------");
		list=dao.getDep();
		return CommonResult.success(list);
	}

2.二级缓存

二级缓存需要手动开启

<!-- 二级缓存  是需要手动开启的  cache -->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />

4.懒查询

在一对多的映射查询中,在collection标签中加入fetchType属性为lazy

<!-- 部门表一对多查询 -->
<resultMap id="departmentAndStaff" type="com.easy.bean.Department"  >
	<!-- <id column="id" property="depid"></id>
	<result column="name" property="depname"></result> -->
	<result column="id" property="id"></result>
	<collection fetchType="lazy" column="id" select="getDepStaff" property="staffList"></collection>
</resultMap>
<!-- 二级缓存  是需要手动开启的  cache -->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />

<select id="getDepStaff" resultType="com.easy.bean.Staff">
	select * from staff where dep_id=#{id}
</select>

<select id="getDep" resultMap="departmentAndStaff">
	select * from department
</select>

  • 22
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值