详解MyBatis直接执行SQL查询及数据批量插入
一、直接执行SQL查询:
1、mappers文件节选
<resultMapid="AcModelResultMap"type="com.izumi.InstanceModel">
<resultcolumn="instanceid"property="instanceID"jdbcType="VARCHAR"/>
<resultcolumn="instancename"property="instanceName"jdbcType="VARCHAR"/>
</resultMap>
<selectid="getInstanceModel"resultType="com.izumi.InstanceModel">
${paramSQL}
</select>
2、DAO类节选
publicinterfaceSomeDAO{
List<InstanceModel>getInstanceModel(@Param("paramSQL")Stringsql);
}
3、注意事项
3.1:传入方法的参数sql必须遵循以下规范"selectXXXasinstanceid,XXXasinstancename.....",否则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、经验告诉我们,使用insertintoXXXvalues(XX)(XXX)(XXX),比使用insertintoXXXvalues(XX),insertintoXXXvalues(XXX),insertintoXXXvalues(XXX)效率要高。
2、在MyBatis中的用法
2.1、mappers文件节选
<insertid="insertBatch">insertintostudent(<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类节选
publicinterfaceSomeDAO{
publicvoidinsertBatch(@Param("list")List<Student>students);
}
详解mybatis批量插入数据
首先看看批处理的mapper.xml文件
<insertid="insertbatch"parameterType="java.util.List">
<selectKeykeyProperty="fetchTime"order="BEFORE"
resultType="java.lang.String">
SELECTCURRENT_TIMESTAMP()
</selectKey>
insertintokangaiduoyaodian(depart1,depart2,product_name,
generic_name,img,product_specification,unit,
approval_certificate,manufacturer,marketPrice,vipPrice,
website,fetch_time,productdesc)values
<foreachcollection="list"item="item"index="index"
separator=",">
(#{item.depart1},#{item.depart2},#{item.productName},
#{item.genericName},#{item.img},
#{item.productSpecification},#{item.unit},
#{item.approvalCertificate},#{item.manufacturer},
#{item.marketprice},#{item.vipprice},#{item.website},
#{fetchTime},#{item.productdesc})
</foreach>
</insert>
在批处理中,我发现有几个需要注意的问题
1、主键的自动获取,在insert中添加useGeneratedKeys=”true”keyProperty=”id”这两个属性无效,并且或中断数据插入,如果id是数据库自增的话,可以什么都不写,在插入的语句中去除主键属性,还有就是利用
<selectKeykeyProperty="id"order="BEFORE" resultType="java.lang.Integer"> SELECTLAST_INSERT_ID() </selectKey>
注意:<selectKey>标签在insert下只能存在一个;批处理的时候不适合使用<selectKey>,主键自增最好,或者指定
2,插入时间的获取如上面所示,我用的是mysql,只要是mysql函数都可以拿来使用,插入时间和主键都是mysql函数中的一个。。。