Introduction to the usage of mapping configuration files in Mybatis

Mybatis mapping configuration file

1, obtaining the value of increment primary key

	<!-- public void addEmp(Employee employee); -->
	<!-- parameterType:参数类型,可以省略, 
	获取自增主键的值:
		mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
		useGeneratedKeys="true";使用自增主键获取主键值策略
		keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性
	-->
	<insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee"
		useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
		insert into tbl_employee(last_name,email,gender) 
		values(#{
    
    lastName},#{
    
    email},#{
    
    gender})
	</insert>

Expand: Oracle does not support auto-increment, Oracle uses sequence to simulate auto-increment; the primary key of each inserted data is the value obtained from the sequence, as shown below:

<!-- 
获取非自增主键的值:
	Oracle不支持自增;Oracle使用序列来模拟自增;
	每次插入的数据的主键是从序列中拿到的值;如何获取到这个值;
 -->
<insert id="addEmp" databaseId="oracle">
	<!-- 
	keyProperty:查出的主键值封装给javaBean的哪个属性
	order="BEFORE":当前sql在插入sql之前运行
		   AFTER:当前sql在插入sql之后运行
	resultType:查出的数据的返回值类型
	
	BEFORE运行顺序:
		先运行selectKey查询id的sql;查出id值封装给javaBean的id属性
		在运行插入的sql;就可以取出id属性对应的值
	AFTER运行顺序:
		先运行插入的sql(从序列中取出新值作为id);
		再运行selectKey查询id的sql;
	 -->
	<selectKey keyProperty="id" order="BEFORE" resultType="Integer">
		<!-- 编写查询主键的sql语句 -->
		<!-- BEFORE-->
		select EMPLOYEES_SEQ.nextval from dual 
		<!-- AFTER:
		 select EMPLOYEES_SEQ.currval from dual -->
	</selectKey>
	
	<!-- 插入时的主键是从序列中拿到的 -->
	<!-- BEFORE:-->
	insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) 
	values(#{id},#{lastName},#{email<!-- ,jdbcType=NULL -->}) 
	<!-- AFTER:
	insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) 
	values(employees_seq.nextval,#{lastName},#{email}) -->
</insert>

2, mybatis processing parameters

​ a) Single parameter: mybatis will not do special processing; #{parameter name/arbitrary name}: Take out the parameter value. example:#{id}

​ b) Multiple parameters: Mybatis will do special processing, multiple parameters will be encapsulated into a map

key:param1...paramN,或者参数的索引也可以 value:传入的参数值

​ If you still follow the writing of a single parameter, #{id},#{lastName}an exception will be thrown (the following code). Here, multiple parameter values ​​need to use named parameters to solve the problem. The example is as follows.

异常:
org.apache.ibatis.binding.BindingException: 
Parameter 'id' not found. 
Available parameters are [1, 0, param1, param2]
操作:
	方法:public Employee getEmpByIdAndLastName(Integer id,String lastName);
	取值:#{id},#{lastName}

​ [Named Parameters]: Clearly specify the key of the map when encapsulating parameters:@Param(“id”)
​ Multiple parameters will be encapsulated into a map:key:使用@Param注解指定的值 value:参数值 #{指定的key}取出对应的参数值

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

C) POJO

​ If multiple parameters happen to be the data model of our business logic, we can directly pass in pojo;#{属性名}:取出传入的pojo的属性值

​ d)Map

If multiple data parameters are not in the business model, there is no corresponding pojo, not often used, for convenience, we can also pass map
#{key}:取出map中对应的值

Summary: parameters for a long time will be packaged map, in order not to chaos, we can use @Param to specify the key used for packaging;

3, the parameter value obtaining (The difference between #{} and ${} in mybatis

​ #{}: You can get the value in the map or the value of the pojo object attribute;
​ ${}: You can get the value in the map or the value of the pojo object attribute;

select * from tbl_employee where id=${id} and last_name=#{lastName}
Preparing: select * from tbl_employee where id=2 and last_name=?
	区别:
		#{}:是以预编译的形式,将参数设置到sql语句中;PreparedStatement;防止sql注入
		${}:取出的值直接拼装在sql语句中;会有安全问题;
		大多情况下,我们去参数的值都应该去使用#{};
		原生jdbc不支持占位符的地方我们就可以使用${}进行取值
	比如分表、排序。。。;按照年份分表拆分
		select * from ${
   
   year}_salary where xxx;
		select * from tbl_employee order by ${f_name} ${
   
   order}

4, when the value of the specified parameters relevant rules

​ #{}: Richer usage:
​ Some rules for specifying parameters:
a) javaType, jdbcType, mode (stored procedure), numericScale, resultMap, typeHandler, jdbcTypeName, expression (functions to be supported in the future);

​ b) jdbcType usually needs to be set under certain conditions:
​ When our data is null, some databases may not recognize mybatis's default handling of null. For example, Oracle (error report);

​ c) JdbcType OTHER: invalid type; because mybatis maps all nulls to the OTHER type of native Jdbc, oracle cannot handle it correctly; due to the global configuration: jdbcTypeForNull=OTHER; oracle does not support; two methods

	1、#{email,jdbcType=NULL};
	2、jdbcTypeForNull=NULL
		<setting name="jdbcTypeForNull" value="NULL"/>	(这里是在mybatis全局配置文件下配置)

5, package records map mapping file -select_

//多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key!!
@MapKey("lastName")
public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);
<!--resultType:如果返回的是一个集合,要写集合中元素的类型  -->
<!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);  -->
 	<select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
 		select * from tbl_employee where last_name like #{lastName}
 	</select> 

6, the results of the mapping file -select_resultMap custom mapping rules

<!--自定义某个javaBean的封装规则
	type:自定义规则的Java类型
	id:唯一id方便引用
	  -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
		<!--指定主键列的封装规则
		id定义主键会底层有优化;
		column:指定哪一列
		property:指定对应的javaBean属性
		  -->
		<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>

7, the mapping file _resultMap_ property associated with the query package cascade results _

Scenario 1:
Query the Employee while querying the department corresponding to the employee
Employee===Department
An employee has department information corresponding to it;
id last_name gender d_id did dept_name (private Department dept;)

Method 1 : joint inquiry:Cascading attributesPackage result set

<resultMap type="com.atguigu.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>

Second way : UsingassociationDefine encapsulation rules for associated single objects

<resultMap type="com.atguigu.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.atguigu.mybatis.bean.Department">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
	</association>
</resultMap>

8. Mapping file_select_resultMap_associated query_distributed query & lazy loading

Use association to perform step-by-step query:
1. First query the employee information according to the employee id
2. Go to the department table to find out the department information according to the d_id value in the query employee information
3. Set the department to the employee;

	 <resultMap type="com.atguigu.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.atguigu.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>	 

	 <!-- 可以使用延迟加载(懒加载);(按需加载)
	 	Employee==>Dept:
	 		我们每次查询Employee对象的时候,都将一起查询出来。
	 		部门信息在我们使用的时候再去查询;
	 		分段查询的基础之上加上两个配置:
	  -->
	<!--在mybatis的全局配置文件中添加懒加载配置-->
	<settings>	
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

​ Scenario 2: ​ When
querying the department, all the employee information corresponding to the department is also queried: the annotation is in the DepartmentMapper.xml

<!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
<select id="getEmpsByDeptId" resultType="com.atguigu.mybatis.bean.Employee">
	select * from tbl_employee where d_id=#{deptId}
</select>

<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则  -->
<!-- 
	public class Department {
			private Integer id;
			private String departmentName;
			private List<Employee> emps;//集合类型得使用collection
	 -->

	<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联集合类型的属性的封装规则 
			ofType:指定集合里面元素的类型
		-->
		<collection property="emps" ofType="com.atguigu.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>
	

9, map file _select_resultMap_discriminator discriminator

<!-- <discriminator javaType=""></discriminator>
		鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
		封装Employee:
			如果查出的是女生:就把部门信息查询出来,否则不查询;
			如果是男生,把last_name这一列的值赋值给email;
	 -->
	 <resultMap type="com.atguigu.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:指定封装的结果类型;不能缺少。/resultMap-->
	 		<case value="0" resultType="com.atguigu.mybatis.bean.Employee">
	 			<association property="dept" 
                             <!--这里是从接口DepartmentMapper中拿到getDeptById方法-->
			 		select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"
			 		column="d_id">
		 		</association>
	 		</case>
	 		<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
	 		<case value="1" resultType="com.atguigu.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>

	 <select id="getEmpByIdStep" resultMap="MyEmpDis">
	 	select * from tbl_employee where id=#{id}
	 </select>

Guess you like

Origin blog.csdn.net/weixin_45496190/article/details/107010151