MyBatis系列目录--6. Mybatis实用技巧
转载请注明出处哈:http://carlosfu.iyunv.com/blog/2238662一、通过数据字典查询列,属性数据(减轻手工、防止错误、结合sql标签使用)
select group_concat(column_name) from information_schema.columns where table_schema = 'football' and table_name = 'club';
# table_schema是数据库名
# club是数据表名
结果:
id,name,info,create_date,rank
二、 下划线命名到驼峰命名
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
三、sql映射中的 # , $ 区分
1. #{}表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。
2. 如果接收简单类型,#{}中可以写成value或其它名称。
#{}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。
3. ${}表示一个拼接符号,会引用sql注入,所以不建议使用${}。
${}接收输入参数,类型可以是简单类型,pojo、hashmap。
如果接收简单类型,${}中只能写成value。
${}属性接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性....的方式获取对象属性值。
四、批量操作:
以批量insert为例子:
(1) dao添加新方法:
/**
* 批量添加俱乐部
* @param clubList
*/
public void batchSave(@Param("clubList") List<Club> clubList);
(2) xml
<insert id="batchSave" parameterType="List" useGeneratedKeys="true">
insert into club(name,info,create_date,rank)
values
<foreach collection="clubList" item="club" index="index" separator=",">
(#{club.name},#{club.info},#{club.createDate},#{club.rank})
</foreach>
</insert>
(3) 测试:
@Test
public void testBatchSave() {
ClubDao clubDao = sqlSession.getMapper(ClubDao.class);
Club club1 = new Club();
club1.setName("Arsenal");
club1.setInfo("阿森纳");
club1.setCreateDate(new Date());
club1.setRank(15);
Club club2 = new Club();
club2.setName("ManUnited");
club2.setInfo("曼联");
club2.setCreateDate(new Date());
club2.setRank(18);
List<Club> clubList = new ArrayList<Club>();
clubList.add(club1);
clubList.add(club2);
clubDao.batchSave(clubList);
}
五、mybatis中的小于号要进行转义,例如:
< 用 <代替
select id,name from table where vid=#{vid} and prod=#{prod} and collect_time >=#{startTime} and collect_time<=#{endTime}
六、批量更新:
<update id="batchUpdate">
<foreach collection="list" item="item" open="" close="" separator=";">
update jf_cdn_vid_hour set normal_count=#{item.normalCount},cheat_count=#{item.cheatCount}
where vid = #{item.vid} and prod= #{item.prod} and collect_time=#{item.collectTime}
</foreach>
</update>
但是jdbc连接要添加allowMultiQueries=true
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/xxdb?allowMultiQueries=true"/>
七、返回Map
例如希望select id,name from table返回Map<Long,String>()
但是事实上,在写mapper.xml时候,返回的是一个List<Map<String,Long>>,然后需要人工解析为你要的Map
<select id="getXXX" resultType="hashmap">
select id,name from table
</select>
Dao:
List<Map<String, Object>> getXXX();
页:
[1]