1、鉴别器 :<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" 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>
2、where(可以自动补充和删除多余的and关键词)、if
<select id="selectByIdAndName" resultType="com.nn.mybatis.entity.Province" databaseId="mysql">
select p.id ,p.province_name,p.country_id
from province p
<where>
<if test="id!=null" >
and p.id=#{id}
</if>
<if test="provinceName!=null || provinceName!=''">
and p.province_name=#{provinceName}
</if>
</where>
</select>
3、choose
<select id="selectByIdAndName2" resultType="com.nn.mybatis.entity.Province" databaseId="mysql">
select p.id ,p.province_name,p.country_id
from province p
<choose>
<when test="id!=null" >
p.id=#{id}
</when>
<when test="provinceName!=null || provinceName!=''">
p.province_name=#{provinceName}
</when>
</choose>
</select>
4、set:可以自动删除多余”,“
<update id="updateProvince">
UPDATE province
<set>
<if test="provinceName!=null">
province_name=#{provinceName},
</if>
<if test="countryId!=null">
country_id=#{countryId},
</if>
</set>
WHERE
id=#{id}
</update>
5、批量保存:
注:需要数据库连接属性allowMultiQueries=true
Mysql下批量保存:
方式一:
<insert id="addEmps">
insert into tbl_employee(
<include refid="insertColumn"></include>
)
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
方式二:
<insert id="addEmps">
<foreach collection="emps" item="emp" separator=";">
insert into tbl_employee(last_name,email,gender,d_id)
values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert> -->
Oracle批量保存:
方式一:
<foreach collection="emps" item="emp" open="begin" close="end;">
insert into employees(employee_id,last_name,email)
values(employees_seq.nextval,#{emp.lastName},#{emp.email});
</foreach>
方式二:引入中间表
insert into employees(employee_id,last_name,email)
<foreach collection="emps" item="emp" separator="union"
open="select employees_seq.nextval,lastName,email from("
close=")">
select #{emp.lastName} lastName,#{emp.email} email from dual
</foreach>
</insert>