Mybatis——SQL映射文件
Mybatis的SQL映射文件和mapper接口文件所对应,反映其接口文件中的方法:
如下有一个一个Employeemapper的SQL映射文件,有4个方法:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chenx.mybatis.dao.EmployeeMapper">
<select id="getEmployeeById" resultType="employee">
select * from tb_employee where id = #{id}
</select>
<insert id="addEmployee"
useGeneratedKeys="true" keyProperty="id">
insert into tb_employee (last_name,email,gender) values(#{lastName},#{email},#{gender})
</insert>
<update id="updateEmployee">
update tb_employee set
last_name=#{lastName},
email=#{email},
gender=#{gender}
where id=#{id}
</update>
<delete id="deleteEmployee">
delete from tb_employee
where id=#{id}
</delete>
</mapper>
有些属性并不只是在这个标签中有,其他标签也有
mapper:
namaspace:命名空间,对应Mapper的全类名
select:
id:方法名
resultType:返回结果类型
insert:
useGeneratedKeys :使用主键自增,(Mysql,sqlserver可用)
keyProperty:指定返回的主键值赋值给对象的哪个属性
如何设置返回主键id
当我们插入一个对象到数据库中时,如何马上获取到它呢,根据其他字段来获取?,可能存在其他一样的值;获取最新的那条记录?,如何同时又有插入一条记录呢,最好是插入成功后返回其主键值:
在SQL映射文件中配置,即可把返回的主键值赋值到我们传入的对象中:
useGeneratedKeys :使用主键自增,(Mysql,sqlserver可用)
keyProperty:指定返回的主键值赋值给对象的哪个属性
参数传递:
当我们在配置SQL映射文件的时候,要编写Sql语句,其中的变量使用#{。。。}来代替,当遇到复杂的情况,我们如何去使用呢.?
1.单个普通类型(基本/包装+string)
当参数只有一个时,如上select语句,只有一个Integer类型的id,我们将变量和属性名使用了一样的名字来对应,其实Mybatis并不会进行处理,所以此时变量名可以任意取;
2.多个参数
当参数方法中参数多于一个时,Mybatis都使用map把我们的参数重新包装,用到map,自然想到key和value,value是我们传入的值,那么key呢,根据我们的习惯,想当然使用对象的属性来命名,实验发现是不行的,其命名方式只能使用0,1,2,3,4…或者是param1,param2,param3,param4.
<select id="getEmployeeByTwo" resultType="employee">
select * from tb_Employee where id=#{0} and last_name=#{1}
</select>
3.命名参数
当参数只有2,3个时使用0,1,2来命名还行,当参数多达10个时,就会记不清哪个参数是干什么的了,所以最好我们能使用自己的命名方式来取名:
public Employee getEmployeeByTwo(@Param("id") Integer id,@Param("lastName") String lastName);
在目标参数的前面使用@Param来指定此参数的名字,接着在SQL映射文件中就可以使用此名字来使用了:
<select id="getEmployeeByTwo" resultType="employee">
select * from tb_Employee where id=#{id} and last_name=#{lastName}
</select>
4.pojo
当我们传递一个pojo对象的时候,我们命名采用属性来命名就可以了:
<update id="updateEmployee">
update tb_employee set
last_name=#{lastName},
email=#{email},
gender=#{gender}
where id=#{id}
</update>
当我们传入多个pojo对象呢?
和使用多个参数时一样,要么默认使用0,1,2,3,4 或者使用@Param来自己命名,获取此对象的某个属性只要加点就行;
<update id="updateEmployee">
update tb_employee set
last_name=#{0.lastName},
email=#{0.email},
gender=#{0.gender}
where id=#{0.id}
</update>
5.mao