MyBatis直接执行SQL查询及批量插入数据

来源:互联网 发布:java jdk版本查看 编辑:程序博客网 时间:2024/05/01 15:51

一、直接执行SQL查询:

 1、mappers文件节选


复制代码
<resultMap id="AcModelResultMap" type="com.izumi.InstanceModel">  <result column="instanceid" property="instanceID" jdbcType="VARCHAR" />  <result column="instancename" property="instanceName" jdbcType="VARCHAR" /></resultMap><select id="getInstanceModel" resultType="com.izumi.InstanceModel">  ${paramSQL} </select>

复制代码

 

2、DAO类节选

public interface SomeDAO{
  List<InstanceModel> getInstanceModel(@Param("paramSQL")String sql);

 

3、注意事项 

3.1:传入方法的参数sql必须遵循以下规范"select XXX as instanceid, XXX as instancename ....." ,否则MyBatis无法自动将查询结果变成Java对象。

3.2: mappers文件中的#{}语法与${}语法的区别:

    默认情况下, #{}语法会促使MyBatis生成PreparedStatement属性并且使用PreparedStatement的参数(=?)来设置值。如果你想直接将未更改的字符串代入到sql中,可以使用${}。

    也就是说,MyBatis看到 #{}会认为你在给sql中的变量赋值,就像JDBC编程中给问号赋值一样(比如MyBatis会判断它的类型,并自动在前后加单引号)。而当MyBatis看到${}的时候会直接将之替换成变量的值而不做任何处理。

所以在使用${}的时候,不需要像#{}一样写"jdbcType=VARCHAR"之类的属性。 

3.3:resultType和resultMap

按照1中的写法, < resultMap > 部分可以删除不用了,因为在接下来的<select >中没用使用定义的resultMap,而是使用了resultType。

所以我们可以看出,关于<select >返回值的定义有两种写法,一种是定义一个resultMap然后引用这个resultMap,还有一种就是直接使用resultType指定一个类的路径。

二、批量插入数据

1、经验告诉我们,使用insert into XXX values(XX)(XXX)(XXX),比使用insert into XXX values(XX),insert into XXX values(XXX),insert into XXX values(XXX)效率要高。

2、在MyBatis中的用法 

2.1、mappers文件节选 

<insertid="insertBatch" >
insert into student (
<includerefid="Base_Column_List" /> )
values
<foreachcollection="list" item="item" index="index" separator=",">
(null,#{item.name},#{item.sex},#{item.address},#{item.telephone},#{item.tId})
</foreach>

</insert> 

 

2.2、DAO类节选

 public interface SomeDAO{

public void insertBatch(@Param("list")List<Student> students); 

 }

 

参考:

1、《MyBatis用户指南中文版》 译者:曾令祝 

2、http://winhack.iteye.com/blog/1522181

 

0 0
原创粉丝点击