<select id="getEmpAndDep" resultType="emp" databaseId="mysql">
select last_name,email,id,gender from employee
where
<if test="id!=null">
id=#{id}
if>
<if test="lastName!=null and lastName!=''">
and last_name like #{lastName}
if>
<if test="gender==0 or gender==1">
and gender=#{gender}
if>
<if test="email!=null and email.trim()!=''">
and email=#{email}
if>
select>
<where>
<if test="id!=null">
id=#{id}
if>
<if test="lastName!=null and lastName!=''">
or last_name like #{lastName}
if>
<if test="gender==0 or gender==1">
and gender=#{gender}
if>
<if test="email!=null and email.trim()!=''">
and email=#{email}
if>
where>
<set>
<if test="lastName!=null">
last_Name=#{lastName},
if>
<if test="email!=null">
email=#{email},
if>
<if test="gender!=null">
gender=#{gender}
if>
set>
<trim prefix="set" suffixOverrides=",">trim>
<trim prefix="WHERE" prefixOverrides="and">trim>
<update id="updateEmp" >
update employee
<set>
<choose>
<when test="lastName!=null">
last_Name=#{lastName},
when>
<when test="email!=null">
email=#{email},
when>
<when test="gender!=null">
gender=#{gender},
when>
<otherwise>
gender=1
otherwise>
choose>
set>
where id=#{id}
update>
用来批量查询
查询语句:select * from employee where id in (1,2,3);
<select id="getByIterator" resultType="emp">
select * from employee where id in
<foreach collection="map" item="item" open="(" close=")" separator=",">
#{item}
foreach>
select>
用来批量插入
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true&&useUnicode=true&&characterEncoding=utf8
第一种:"BatchInsert" >
insert into employee (last_name,email,gender)Values
<foreach collection="list" item="item" separator=",">
(#{item.lastName},#{item.email},#{item.gender})
foreach>
第二种
"BatchInsert2" >
<foreach collection="list" item="item" separator=";">
insert into employee (last_name,email,gender)Values
(#{item.lastName},#{item.email},#{item.gender})
foreach>
sql语句
begin
insert into employee (last_name,email,gender)
Values ("hou","[email protected]",1);
insert into employee (last_name,email,gender)
Values ("hou","[email protected]",1);
end;
foreach代码
"BatchInsert2" >
<foreach collection="list" item="item" open="begin" close="end">
insert into employee (id,last_name,email,gender)Values
(employee_seq.nextval,#{item.lastName},#{item.email},#{item.gender})
foreach>
insert into employee (id,last_name,gender,email)
select employeeseq.nextval,last_name,gender,email from(
select "[email protected]" email,"hou" last_name,0 gender from dual union
select "[email protected]" email,"hou" last_name,0 gender from dual
)
foreach语句
"BatchInsert2" >
insert into employee (id,last_name,gender,email)
select employee_seq.nextval,last_name,gender,email from(
<foreach collection="list" item="item" separator="union">
select #{item.lastName} last_name,#{item.email} email,#{item.gender} gender
foreach>