【Mybatis学习笔记】—— 【三】sql映射文件

需要更好的阅读的体验请移步 👉 小牛肉的个人博客 👈



映射文件指导着MyBatis如何进行数据库增删改查, 有着非常重要的意义;

  • cache –命名空间的二级缓存配置
  • cache-ref – 其他命名空间缓存配置的引用
  • resultMap – 自定义结果集映射
  • parameterMap – 已废弃!老式风格的参数映射
  • sql –抽取可重用语句块。
  • insert – 映射插入语句
  • update – 映射更新语句
  • delete – 映射删除语句
  • select – 映射查询语句

一、增删改查 insert、update、delete、select

select 元素在第一章已经学习过了,接下来看 insert, update, delete 元素,在第一章代码的基础上完成一套完整的 CRUD 流程

sql映射文件:

<mapper namespace="com.smallbeef.mybatis.dao.EmployeeMapper">
    <!--id:唯一标识
    resultType: 返回值类型
    #{id}:从传递过来的参数中取出id值-->

    <!--public Employee getEmpById(Integer id)
    将唯一标识id和接口中的方法进行绑定-->
    <select id="getEmpById" resultType="com.smallbeef.mybatis.bean.Employee">
        select id, last_name lastName, email, gender from tbl_employee where id = #{id}
    </select>

    <!--public Integer addEmp(Employee employee);-->
    <insert id = "addEmp">
        insert into tbl_employee(last_name, email, gender) values(#{lastName}, #{email}, #{gender})
    </insert>

    <!--public boolean updateEmp(Employee employee);-->
    <update id="updateEmp" >
        update tbl_employee
        set last_name = #{lastName}, email = #{email}, gender = #{gender}
        where id = #{id}
    </update>

    <!--public void deleteEmpById(Integer id);-->
    <delete id="deleteEmpById">
        delete from tbl_employee
        where id = #{id}
    </delete>


</mapper>

mybatis允许增删改直接定义以下类型返回值

  • Integer
  • Long
  • Boolean
  • void

Dao层接口类:

public interface EmployeeMapper {

    /**
     * 查找
     * @param id
     * @return
     */
    public Employee getEmpById(Integer id);

    /**
     * 更新
     * @param employee
     * @return
     */
    public boolean updateEmp(Employee employee);

    /**
     * 添加
     * @param employee
     * @return
     */
    public Integer addEmp(Employee employee);

    /**
     * 删除
     * @param id
     */
    public void deleteEmpById(Integer id);
}

同时别忘了在JavaBean类中添加无参构造函数和构造函数,以及在全局配置文件中注册sql映射文件

  /**
     * 测试增删改
     *   * 1、mybatis允许增删改直接定义以下类型返回值
     * 	 * 		Integer、Long、Boolean、void
     * 	 * 2、我们需要手动提交数据
     * 	 * 		sqlSessionFactory.openSession();===》手动提交
     * 	 * 		sqlSessionFactory.openSession(true);===》自动提交
     * @throws IOException
     */
    @Test
    public void test02() throws  IOException{
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

            // 测试插入
            Employee jack = new Employee(null, "Jack", "1", "[email protected]");
            mapper.addEmp(jack);

            // 测试修改
            Employee jack123 = new Employee(2, "Jack123", "0", "[email protected]");
            mapper.updateEmp(jack123);

            // 测试删除
            mapper.deleteEmpById(2);

            //必须手动提交数据
            sqlSession.commit();

        }finally {
            sqlSession.close();
        }

    }

注意一定要手动提交数据 sqlSession.commit();

因为我们是这样打开的 sqlSessionFactory.openSession();
可以通过 sqlSessionFactory.openSession(true); 来设置自动提交

二、insert 获取自增主键的值

若数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),
则可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上。

<insert id="addEmp" parameterType="com.smallbeef.mybatis.bean.Employee"
		useGeneratedKeys="true" keyProperty="id">
		insert into tbl_employee(last_name,email,gender) 
		values(#{lastName},#{email},#{gender})
</insert>

三、参数处理

1. 单个参数

单个参数:mybatis不会做特殊处理,
#{参数名/任意名}:取出参数值。

例如:

public Employee getEmpById(Integer id);

不一定非要通过 #{id} 取出参数值,任意参数名都可取出,比如 #{abc}

<select id="getEmpById" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where id = #{abc}
</select>

2. 多个参数

多个参数的情况下,按照上面的方法取值会报错,比如:

public Employee getEmpByIdAndLastName(Integer id,String lastName);

-------------------------------------------------------------------

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 </select>

报错如下:

org.apache.ibatis.binding.BindingException: 
	Parameter 'id' not found. 
	Available parameters are [1, 0, param1, param2]

任意多个参数,都会被MyBatis重新包装成一个Map传入。
key:param1…paramN, 或者参数的索引也可以
value:传入的参数值

#{ }就是从map中获取指定的key的值;

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{param1} and last_name=#{param2}
 </select>

3. @Param 命名参数

多个参数用上述这样的方法看起来不太直观,于是我们可以使用注解 @Param 为参数起一个名字,MyBatis就会将这些参数封 装进map中,key就是我们自己指定的名字

举例如下:

public Employee getEmpByIdAndLastName(@Param("id")Integer id,@Param("lastName")String lastName);

---------------------------------------------------------------------------------------

<select id="getEmpByIdAndLastName" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id = #{id} and last_name=#{lastName}
 </select>

4. POJO

如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo;
#{属性名}:取出传入的pojo的属性值

举例如下:

public boolean updateEmp(Employee employee);

-------------------------------------------------------------

<update id="updateEmp">
		update tbl_employee 
		set last_name=#{lastName},email=#{email},gender=#{gender}
		where id=#{id}
</update>

5. Map

如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以封装多个参数为map,直接传递
#{key}:取出map中对应的值

举例如下:

public Employee getEmpByMap(Map<String, Object> map);

---------------------------------------------------------------------

<select id="getEmpByMap" resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where id=${id} and last_name=#{lastName}
</select>
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//Employee employee = mapper.getEmpByIdAndLastName(1, "tom");
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("lastName", "Tom");
Employee employee = mapper.getEmpByMap(map);

6. TO

如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个 TO(Transfer Object) 数据传输对象

比如分页模型

Page{
	int index;
	int size;
	......
}

参数处理综合示例

public Employee getEmp(@Param("id")Integer id,String lastName);

取值:

  • id —> #{id / param1}
  • lastName —> #{param2}
public Employee getEmp(Integer id,@Param("e")Employee emp);

取值:

  • id —> #{param1}
  • lastName —> #{param2.lastName / e.lastName}

特别注意:
如果是Collection(List、Set)类型或者是数组,也会特殊处理。也是把传入的list或者数组封装在map中。

  • Collection:则对应 key 为 collection
  • List:则对应 key 为 collection 或者 list

举例如下:

public Employee getEmpById(List<Integer> ids);

取值:
取出第一个id的值: # {list[0]}

参数处理 $ 和 # 的区别

  • #{} :可以获取map中的值或者pojo对象属性的值;
  • ${} :可以获取map中的值或者pojo对象属性的值;
select * from tbl_employee where id=${id} and last_name=#{lastName}

输出如下:

Preparing: select * from tbl_employee where id=2 and last_name=?

区别:

  • #{}: 是以预编译的形式,将参数设置到sql语句中,防止sql注入
  • ${}: 取出的值直接拼装在sql语句中;会有安全问题;

大多情况下,我们去参数的值都应该去使用#{};

原生jdbc不支持占位符的地方我们就可以使用${}进行取值
比如分表、排序。。。;

举例如下:

按照年份分表拆分

select * from ${year}_salary where xxx;
select * from tbl_employee order by ${f_name} ${order}

三、select 元素

Select元素来定义查询操作。

  • Id:唯一标识符。 – 用来引用这条语句,需要和接口的方法名一致
  • parameterType:参数类型。 – 可以不传,MyBatis会根据TypeHandler自动推断
  • resultType:返回值类型。 – 别名或者全类名,如果返回的是集合,定义集合中元 素的类型。不能和 resultMap 同时使用

1. resultType 返回值类型

返回类型是对象的情况我们之前已经反复使用过了,下面来讲解以下其他返回类型

a. 返回 List

如果返回的是集合,resultType 中定义集合中元素的类型,比如下面代码中的 Employee

public List<Employee> getEmpsByLastNameLike(String lastName);
	
--------------------------------------------------------------

	<!--resultType:如果返回的是一个集合,要写集合中元素的类型  -->
	<select id="getEmpsByLastNameLike" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where last_name like #{lastName}
	</select>

测试:

List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
			for (Employee employee : like) {
				System.out.println(employee);
}

b. 返回 Map

resultmap = "map"

返回一条记录

返回一条记录的map;key就是列名,值就是对应的值

public Map<String, Object> getEmpByIdReturnMap(Integer id);

-------------------------------------------------------

<select id="getEmpByIdReturnMap" resultType="map">
 		select * from tbl_employee where id=#{id}
</select>

测试:

Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
			System.out.println(map);

结果:

{id = 1, [email protected], last_name = Jack, gender = 0}

返回多条记录

  • 多条记录封装一个map:Map<Integer,Employee> : 键是这条记录的主键,值是记录封装后的javaBean
  • @MapKey : 告诉mybatis封装这个map的时候使用哪个属性作为map的key
	@MapKey("lastName")
	public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);

-----------------------------------------------------------------------

<select id="getEmpByLastNameLikeReturnMap" 	
	resultType="com.smallbeef.mybatis.bean.Employee">
 		select * from tbl_employee where last_name like #{lastName}
</select>

测试:

Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
			System.out.println(map);

结果:

{Jack = Employee[id = 1, lastName = Jack, email = [email protected], gender = 0],Tom = Employee[id = 2, lastName = Tom, email = [email protected], gender = 1]}

2. resultMap 自定义结果集映射规则

resultType 自定义某个javaBean的封装规则

参数:

  • type:自定义规则的 JavaBean 类型
  • id:唯一id方便引用

标签:

  • id : 定义主键
  • result:定义其他普通键

标签属性:

  • column : 数据库表的列名
  • property : 对应的JavaBean属性
<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MySimpleEmp">
	<!--指定主键列的封装规则
	id 定义主键会底层有优化;
		column:指定哪一列
		property:指定对应的javaBean属性
	result 定义普通列封装规则 
	 -->
	<id column="id" property="id"/>
	
	
	<result column="last_name" property="lastName"/>
	<!-- 其他不指定的列会自动封装:但是 推荐 我们只要写resultMap就把全部的映射规则都写上-->
	<result column="email" property="email"/>
	<result column="gender" property="gender"/>
</resultMap>

<!-- resultMap:自定义结果集映射规则;  -->
<!-- public Employee getEmpById(Integer id); -->
<select id="getEmpById"  resultMap="MySimpleEmp">
	select * from tbl_employee where id=#{id}
</select>

3. resultMap 联合查询:级联属性封装结果集

  • POJO中的属性可能会是一个对象
  • 我们可以使用联合查询,并以级联属性的方式封装对象。

例如:
员工表中含有部门对象

实体类:

public class Employee {
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	private Department dept;


--------------------------------------------------

public class Department {
	private Integer id; //数据库表字段id
	private String departmentName; //数据库表字段dept_name

接口:

public Employee getEmpAndDept(Integer id);

映射文件:

employee中内嵌对象dept的属性通过dept.id、dept.departmentName等来获取

<!--
		联合查询:级联属性封装结果集
	  -->
	<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyDifEmp">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		<result column="did" property="dept.id"/>
		<result column="dept_name" property="dept.departmentName"/>
	</resultMap>

<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

4. resultMap association:嵌套结果集

使用association定义关联的单个对象的封装规则

association 标签可以指定联合的 javaBean 对象

  • property = “dept” :指定哪个属性是联合的对象
  • javaType : 指定这个属性对象的类型[不能省略]
	<!-- 
		使用association定义关联的单个对象的封装规则;
	 -->
	<resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyDifEmp2">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="gender" property="gender"/>
		
		<!--  association可以指定联合的javaBean对象
		property="dept":指定哪个属性是联合的对象
		javaType:指定这个属性对象的类型[不能省略]
		-->
		<association property="dept" javaType="com.smallbeef.mybatis.bean.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
	</resultMap>

<!--  public Employee getEmpAndDept(Integer id);-->
	<select id="getEmpAndDept" resultMap="MyDifEmp2">
		SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
		d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
		WHERE e.d_id=d.id AND e.id=#{id}
	</select>

5. resultMap association:分步查询

使用 association 进行分步查询:

  • 先按照员工 id 查询员工信息
select * from tbl_employee where id = 1;
  • 根据查询到的员工信息中的 d_id 值去部门表查出部门信息
select * from tbl_dept where id = 1;
  • 将部门信息设置到员工中;

association 标签的相关属性

  • select : 表明当前属性是调用select指定的方法查出的结果
  • column : 指定将哪一列的值传给这个方法

流程 :使用 select 指定的方法(传入column 指定的这列参数的值)查出对象,并封装给 property 指定的属性

 <!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- association定义关联对象的封装规则
	 		select:表明当前属性是调用select指定的方法查出的结果
	 		column:指定将哪一列的值传给这个方法
	 		
	 		流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
	 	 -->
 		<association property="dept" 
	 		select="com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>

其中,根据部门id查询部门信息 getDeptById 如下:

public Department getDeptByIdStep(Integer id);

-------------------------------------------

<select id="getDeptById" resultType="com.smallbeef.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>

5. resultMap association:分步查询 & 延迟加载

在分步查询基础上实现延迟加载(懒加载)

在全局配置文件中开启延迟加载和属性按需加载

<settings>	
		<!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

6. resultMap collection:嵌套结果集

场景:查询部门的时候将部门对应的所有员工信息也查询出来

部门表对应的JavaBean,内嵌员工信息的集合属性

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
public List<Employee> getEmpsByDeptId(Integer deptId);

--------------------------------------------

	<select id="getEmpsByDeptId" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>

collection 标签定义关联集合类型的属性的封装规则
参数:

  • property :指定要封装到哪个集合属性(本例中封装到部门对象中的 emps 属性)
  • ofType : 指定集合里面元素的类型
<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
	<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则 
			ofType:指定集合里面元素的类型
		-->
		<collection property="emps" ofType="com.smallbeef.mybatis.bean.Employee">
			<!-- 定义这个集合中元素的封装规则 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
	</resultMap>


	<!-- public Department getDeptByIdPlus(Integer id); -->
	<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.last_name last_name,e.email email,e.gender gender
		FROM tbl_dept d
		LEFT JOIN tbl_employee e
		ON d.id=e.d_id
		WHERE d.id=#{id}
	</select>
	

7. resultMap collection:分步查询

需求:根据部门id查询该部门下所有的员工信息

  • 根据部门id查询部门信息
  • 根据部门id查询员工信息
<!-- collection:分段查询 -->
<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDeptStep">
	<id column="id" property="id"/>
	<id column="dept_name" property="departmentName"/>
	<collection property="emps" 
		select="com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
		column="id">
	</collection>
</resultMap>


<!-- public Department getDeptByIdStep(Integer id); -->
<select id="getDeptByIdStep" resultMap="MyDeptStep">
	select id,dept_name from tbl_dept where id=#{id}
</select>

其中根据部门id查询员工信息 getEmpsByDeptId

public List<Employee> getEmpsByDeptId(Integer deptId);

-------------------------------------------

	<select id="getEmpsByDeptId" resultType="com.smallbeef.mybatis.bean.Employee">
		select * from tbl_employee where d_id=#{deptId}
	</select>

8. resultMap collection:多列值封装map & 懒加载

分步查询的时候通过column指定,将对应的列的数据 传递过去,我们有时需要传递多列数据 :将多列的值封装map传递;
column="{key1=column1,key2=column2}"
key是方法中的形参,column是数据库表列名


fetchType="lazy" :表示使用延迟加载,该标签可以覆盖全局的延迟加载策略

  • lazy:延迟
  • eager:立即
<resultMap type="com.smallbeef.mybatis.bean.Department" id="MyDeptStep">
		<id column="id" property="id"/>
		<id column="dept_name" property="departmentName"/>
		<collection property="emps" 
			select="com.smallbeef.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
			column="{deptId=id}" fetchType="lazy"></collection>
	</resultMap>

9. resultMap discriminator 鉴别器

鉴别器:mybatis可以使用 discriminator 判断某列的值,然后根据某列的值改变封装行为

<discriminator javaType=" " column = " "></discriminator>
属性:

  • column:指定判定的列名
  • javaType:列值对应的java类型

场景:

  • 如果查出的是女生:就把部门信息查询出来,否则不查询;
  • 如果是男生,把last_name这一列的值赋值给email;
 <resultMap type="com.smallbeef.mybatis.bean.Employee" id="MyEmpDis">
 	<id column="id" property="id"/>
 	<result column="last_name" property="lastName"/>
 	<result column="email" property="email"/>
 	<result column="gender" property="gender"/>
 	<!--
 		column:指定判定的列名
 		javaType:列值对应的java类型  -->
 	<discriminator javaType="String" column="gender">
 		<!--女生  resultType:指定封装的结果类型;不能缺少-->
 		<case value="0" resultType="com.smallbeef.mybatis.bean.Employee">
 			<association property="dept" 
		 		select="com.smallbeef.mybatis.dao.DepartmentMapper.getDeptById"
		 		column="d_id">
	 		</association>
 		</case>
 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
 		<case value="1" resultType="com.smallbeef.mybatis.bean.Employee">
	 		<id column="id" property="id"/>
		 	<result column="last_name" property="lastName"/>
		 	<result column="last_name" property="email"/>
		 	<result column="gender" property="gender"/>
 		</case>
 	</discriminator>
 </resultMap>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章