[关闭]
@zero1036 2019-03-08T07:17:47.000000Z 字数 5383 阅读 1074

MyBatis配置技巧

Java-ORM


提纲与学习路线

  1. mybatis搭建简单入门:http://www.cnblogs.com/xdp-gacl/p/4261895.html
  2. 基础crud:http://www.cnblogs.com/xdp-gacl/p/4262895.html
  3. resultMap嵌套对象:http://www.cnblogs.com/hamhog/p/3959451.html
  4. resultMap与parameterMap相同,如何避免重复编写;答:参数直接使用parameterType指向Class,绑定字段
  5. 如何调用存储过程:http://blog.csdn.net/u012948731/article/details/49003361
  6. mysql查询分页:http://blog.csdn.net/ls_man/article/details/11783813
  7. parameterType类型为List的配置方法:http://blog.csdn.net/lsq_401/article/details/46776223

Conf配置

通过Maven打包时,默认情况下不会打包src目录下的xml文件,因此,如下结构会报错Could not find resource com.tg.mybatis.lotteryMapper.xml

image_1bksotdah1dh1164213356qr1idpg.png-5.6kB

  1. <configuration>
  2. <environments default="development">
  3. <environment id="development">
  4. <transactionManager type="JDBC"/>
  5. <!-- 配置数据库连接信息 -->
  6. <dataSource type="POOLED">
  7. <property name="driver" value="com.mysql.jdbc.Driver"/>
  8. <property name="url" value="xxx"/>
  9. <property name="username" value="u"/>
  10. <property name="password" value="pwd"/>
  11. </dataSource>
  12. </environment>
  13. </environments>
  14. <mappers>
  15. <mapper resource="com/tg/mybatis/lotteryMapper.xml"/>
  16. </mappers>
  17. </configuration>

Maven Mapper.xml建议添加到resources目录中,<mappers/>调整:

  1. <mappers>
  2. <mapper resource="mapper/lotteryMapper.xml"/>
  3. </mappers>

Mapper配置

parameterType

http://blog.csdn.net/kingjin_csdn_/article/details/53156732

  1. MyBatis的传入参数parameterType类型分两种

      1. 基本数据类型:int,string,long,Date;
      1. 复杂数据类型:类和Map
        注:不同版本的MyBatis对基本类型传递过来的参数名称不能识别,要使用_parameter来代替。
        [html] view plain copy print?

        select from win_log where eventId = #{_parameter,jdbcType=BIGINT}
  2. 如何获取参数中的值:
    2.1 基本数据类型:#{参数} 获取参数中的值
    2.2 复杂数据类型:#{属性名} ,map中则是#{key}


resultType


【foreach】标签

xml语法:

  1. <foreach collection="list" item="item" open="(" close=")" separator="," index="index">
  2. #{item.xx}, #{item.xx}
  3. </foreach>
项目 价格
collection="list" 其中list是固定的,如果是数组就是array
item="item" 循环中每一项的别名
open="" 开始标识,比如删除in (id1,id2), open="(" close=")"
close="" 结束标识
separator="," 分隔符号
index="index" 下标值

> 单参数List的类型:

code:List ids = new ArrayList();List blogs = blogMapper.dynamicForeachTest(ids);

  1. <select id="dynamicForeachTest" parameterType="java.util.List" resultType="Blog">
  2. select * from t_blog where id in
  3. <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </select>

> 自己把参数封装成Map的类型

注意:上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
public List dynamicForeach3Test(Map params);

code:

  1. List ids = new ArrayList();List blogs = blogMapper.dynamicForeachTest(ids);
  2. final List ids = new ArrayList();
  3. ids.add(1);
  4. ids.add(2);
  5. ids.add(3);
  6. ids.add(6);
  7. ids.add(7);
  8. ids.add(9);
  9. Map params = new HashMap();
  10. params.put("ids", ids);
  11. params.put("title", "中国");
  12. List blogs = blogMapper.dynamicForeach3Test(params);
  1. <select id="dynamicForeach3Test" parameterType="java.util.HashMap" resultType="Blog">
  2. select * from t_blog where title like "%"#{title}"%" and id in
  3. <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </select>
  1. <select id="findListByNos" parameterType="list" resultMap="BaseResultMap">
  2. SELECT
  3. <include refid="Base_Column_List"/>
  4. FROM INFO
  5. WHERE INFO_ID IN
  6. <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
  7. #{item}
  8. </foreach>
  9. ORDER BY INFO_ID DESC
  10. </select>
  11. <select id="findById" resultMap="BaseResultMap" parameterType="java.lang.String" >
  12. SELECT
  13. <include refid="Base_Column_List" />
  14. FROM INFO
  15. WHERE INFO_ID = #{infoId,jdbcType=VARCHAR}
  16. </select>
  17. <select id="findByEntityWithPagination" resultMap="BaseResultMap" >
  18. SELECT
  19. <include refid="Base_Column_List" />
  20. FROM INFO
  21. <trim prefix="WHERE" suffixOverrides="AND" >
  22. <if test="param1.infoType != null" >
  23. INFO_TYPE = #{param1.infoType,jdbcType=VARCHAR} AND
  24. </if>
  25. <if test="param1.infoContent != null" >
  26. INFO_CONTENT = #{param1.infoContent,jdbcType=LONGVARCHAR} AND
  27. </if>
  28. </trim>
  29. LIMIT #{param2} , #{param3}
  30. </select>
  31. <select id="findByProperties" parameterType="map" resultMap="BaseResultMap" >
  32. SELECT
  33. <include refid="Base_Column_List" />
  34. FROM INFO
  35. <trim prefix="WHERE" suffixOverrides="AND" >
  36. <if test="_parameter.containsKey('infoType')" >
  37. INFO_TYPE = #{infoType,jdbcType=VARCHAR} AND
  38. </if>
  39. <if test="_parameter.containsKey('infoContent')" >
  40. INFO_CONTENT = #{infoContent,jdbcType=LONGVARCHAR} AND
  41. </if>
  42. <if test="_parameter.containsKey('infoName')" >
  43. INFO_NAME = #{infoName,jdbcType=VARCHAR} AND
  44. </if>
  45. </trim>
  46. ORDER BY INFO_ID
  47. </select>
  48. <select id="findByEntity" resultMap="BaseResultMap" parameterType="com.cn.Info" >
  49. SELECT
  50. <include refid="Base_Column_List" />
  51. FROM INFO
  52. <trim prefix="WHERE" suffixOverrides="AND" >
  53. <if test="infoType != null" >
  54. INFO_TYPE = #{infoType,jdbcType=VARCHAR} AND
  55. </if>
  56. <if test="infoContent != null" >
  57. INFO_CONTENT = #{infoContent,jdbcType=LONGVARCHAR} AND
  58. </if>
  59. </trim>
  60. </select>

批量插入

  1. //java code
  2. int id = mapper.batchSave(List<User> list)
  3. <!-- 批量保存用户,并返回每个用户插入的ID -->
  4. <insert id="batchSave" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
  5. INSERT INTO `test`.`tb_user`(`username`, age)
  6. VALUES
  7. <foreach collection="list" item="item" separator=",">
  8. (#{item.username}, #{item.age})
  9. </foreach>
  10. </insert>

【insert】

insert插入返回主键ID

很多时候,在向数据库插入数据时,需要保留插入数据的id,以便进行后续的update操作或者将id存入其他表作为外键。但是,在默认情况下,insert操作返回的是一个int值,并且不是表示主键id,而是表示当前SQL语句影响的行数。。。

MyBatis在使用MySQL insert插入操作时将返回的id绑定到对象中。

MySQL用法:

  1. <insert id="insert" parameterType="com.test.User" keyProperty="userId" useGeneratedKeys="true" >

上面配置中,“keyProperty”表示返回的id要保存到对象的那个属性中,“useGeneratedKeys”表示主键id为自增长模式。


【if】标签

    <if test="_parameter != null and _parameter > 0">
        AND id = #{_parameter}
    </if>

    连接符and必须小写,否则报错,限定以下

        <EOF> 
"," ...
"=" ...
"?" ...
"||" ...
"or" ...
"&&" ...
"and" ...
"|" ...
"bor" ...
"^" ...
"xor" ...
"&" ...
"band" ...
"==" ...
"eq" ...
"!=" ...
"neq" ...
"<" ...
"lt" ...
">" ...
"gt" ...
"<=" ...
"lte" ...
">=" ...
"gte" ...
"in" ...
"not" ...
"<<" ...
"shl" ...
">>" ...
"shr" ...
">>>" ...
"ushr" ...
"+" ...
"-" ...
"*" ...
"/" ...
"%" ...
"instanceof" ...
"." ...
"(" ...
"[" ...
<DYNAMIC_SUBSCRIPT> ...

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注