您的位置:首页 > 数据库

Mybatis 转义字符,动态sql , 批量插入,批量更新

2014-07-05 10:20 429 查看

MyBatis
Sql语句中的转义字符

1、在xml的sql语句中,不能直接用大于号、小于号要用转义字符

如果用小于号会报错误如下:

org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.

转义字符
<
<
小于号
>
>
大于号
&
&

'

单引号
"
"
双引号
2、使用

<![CDATA[ ]]>标记的sql语句中的<where> <if>等标签不会被解析

Mybatis 动态sql

MyBatis中用于实现动态SQL的元素主要有:

if
choose(when,otherwise)
trim
where
set
foreach

<select id="selectByLoginName" resultMap="UserResultMap"

parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from tbl_user
where login_name =#{loginName,jdbcType=VARCHAR}
</select>

例子一:
<select id="getPage" resultMap="OutcallTaskMap" parameterType="java.util.Map" >
select * from (
select a.*,b.plan_name,c.act_name as market_name,d.audience_name
from tbl_outcalltask a ,tbl_delivery_info b ,tbl_market_act c, tbl_audience d
where a.deliveryid=b.id and b.market_id = c.id and b.audience_id = d.id
) ta where 1=1

<if test="planName != null" >
<if test="outcalltype != null" >
<choose>
<when test="outcalltype =="1" "><![CDATA[ and ta.plan_name like '%${planName}%' ]]></when>
<when test="outcalltype =="0" "><![CDATA[ and ta.market_name like '%${planName}%' ]]></when>
</choose>
</if>
</if>

<if test="startTime != null" >
<if test="outcalltype != null" >
<choose>
<when test="outcalltype =="1" "><![CDATA[ and ta.create_time >= #{startTime} ]]></when>
<when test="outcalltype =="0" "><![CDATA[ and ta.last_download_time >= #{startTime} ]]></when>
</choose>
</if>
</if>

<if test="endTime != null" >
<if test="outcalltype != null" >
<choose>
<when test="outcalltype == "1" "><![CDATA[ and ta.create_time <= #{endTime} ]]></when>
<when test="outcalltype == "0" "><![CDATA[ and ta.last_download_time <= #{endTime} ]]></when>
</choose>
</if>
</if>

<if test="deliveryid != null" >
and ta.deliveryid = #{deliveryid}
</if>
<if test="outcalltype != null" >
and ta.outcalltype = #{outcalltype}
</if>
<if test="workCompanyId != null" >
and ta.company_id = #{workCompanyId}
</if>
order by ta.last_mofify_time desc
</select>

choose 的完整语法
<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
and content = #{content}
</when>
<otherwise>
and owner = "owner1"
</otherwise>
</choose>
</select>

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能

<select id="isExist" resultType="java.lang.Integer"
parameterType="com.geo.app.org.model.User">
select count(*) from tbl_user
<trim prefix="where (" suffixOverrides="or" suffix=")">
<if test="loginName != null and loginName != ''">
login_name = #{loginName,jdbcType=VARCHAR} or
</if>
<if test="userName != null and userName != ''">
user_name = #{userName,jdbcType=VARCHAR} or
</if>
</trim>
<if
test="((loginName != null and loginName != '') or (userName != null and userName != '')) and id != null">
and id != #{id,jdbcType=INTEGER}
</if>
limit 0,1
</select>

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:

如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

1.单参数List的类型:
<select id="dynamicForeachTest" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
public List<Blog> dynamicForeachTest(List<Integer> ids);
@Test
public void dynamicForeachTest() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(6);
List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}

2.单参数array数组的类型:
<select id="dynamicForeach2Test" resultType="Blog">
select * from t_blog where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
public List<Blog> dynamicForeach2Test(int[] ids);

@Test
public void dynamicForeach2Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
int[] ids = new int[] {1,3,6,9};
List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}

3 自己把参数封装成Map的类型
<select id="dynamicForeach3Test" resultType="Blog">
select * from t_blog where title like "%"#{title}"%" and id in
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>

public List<Blog> dynamicForeach3Test(Map<String, Object> params);

@Test
public void dynamicForeach3Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
final List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(6);
ids.add(7);
ids.add(9);
Map<String, Object> params = new HashMap<String, Object>();
params.put("ids", ids);
params.put("title", "中国");
List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}

项目中的例子:

<insert id="insertBatchBusiness_people" parameterType="map">
insert into tbl_business_people_#{businessId} (business_id,uid)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.business_id,jdbcType=VARCHAR},
#{item.uid,jdbcType=VARCHAR}
)
</foreach>
ON DUPLICATE KEY UPDATE updatetime=NOW()

</insert>

dao 层:
public Integer insertBatchBusiness_people(@Param("businessId") Integer businessId,
@Param("list") List<Business_peopleEntity> list);

sevice interface 层
public Integer insertBatchBusiness_people(List<Business_peopleEntity> item);

sevice impl 层
@Override
public Integer insertBatchBusiness_people(
List<Business_peopleEntity> item) {
return business_peopleDao.insertBatchBusiness_people(item.get(0).getBusiness_id(),item);
}

<insert id="insertBatchSelect" parameterType="java.util.List">
insert into tbl_outcalldetail (outcalltaskid, user_id,
telephoneNo, typeno1,
price_range1, typeno2, price_range2,
typeno3, price_range3, kw,
url, recommend, state,
isaccept, remark, outcalluserid,
outcallusername, outcalltime) values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.outcalltaskid,jdbcType=INTEGER}, #{item.userId,jdbcType=VARCHAR},
#{item.telephoneno,jdbcType=VARCHAR}, #{item.typeno1,jdbcType=VARCHAR},
#{item.priceRange1,jdbcType=VARCHAR}, #{item.typeno2,jdbcType=VARCHAR},
#{item.priceRange2,jdbcType=VARCHAR}, #{item.typeno3,jdbcType=VARCHAR},
#{item.priceRange3,jdbcType=VARCHAR}, #{item.kw,jdbcType=VARCHAR},
#{item.url,jdbcType=VARCHAR}, #{item.recommend,jdbcType=VARCHAR}, #{item.state,jdbcType=INTEGER},
#{item.isaccept,jdbcType=INTEGER}, #{item.remark,jdbcType=VARCHAR}, #{item.outcalluserid,jdbcType=INTEGER},
#{item.outcallusername,jdbcType=VARCHAR}, #{item.outcalltime,jdbcType=TIMESTAMP}
)
</foreach>
</insert>

<update id="updateBatchByPrimaryKeySelective" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update tbl_outcalldetail
<set >
<if test="item.state != null" >
state = #{item.state,jdbcType=INTEGER},
</if>
<if test="item.isaccept != null" >
isaccept = #{item.isaccept,jdbcType=INTEGER},
</if>
<if test="item.remark != null" >
remark = #{item.remark,jdbcType=VARCHAR},
</if>
<if test="item.outcalluserid != null" >
outcalluserid = #{item.outcalluserid,jdbcType=INTEGER},
</if>
<if test="item.outcallusername != null" >
outcallusername = #{item.outcallusername,jdbcType=VARCHAR},
</if>
<if test="item.outcalltime != null" >
outcalltime = #{item.outcalltime,jdbcType=TIMESTAMP},
</if>
</set>
where 1=1
<if test="item.outcalldetailid !=null" >
and id = #{item.outcalldetailid,jdbcType=INTEGER}
</if>
<if test="item.outcalltaskid !=null" >
and outcalltaskid = #{item.outcalltaskid,jdbcType=INTEGER}
</if>
<if test="item.userId !=null" >
and user_id = #{item.userId,jdbcType=VARCHAR}
</if>
</foreach>
</update>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: