MyBatis 常用写法

绝地灬酷狼 2021-12-16 08:41 515阅读 0赞

https://blog.csdn.net/javadhh/article/details/52422242

实际项目总结的一些用法,以后用相似的可以直接拷贝

foreach**用法:**

  1. /**
  2. * 查询出用户最大的登录时间
  3. * @param informedObjIds 用户id集合
  4. * @return
  5. */
  6. List<UserLastLoginBean> selectUserMaxLoginTimeByUserIds(
  7. List<Integer> informedObjIds);
  8. <resultMap id="MaxLoginTimeMap" type="com.clou.douliu.server.bean.UserLastLoginBean">
  9. <id column="userId" property="userId" jdbcType="INTEGER" />
  10. <result column="maxLoginTime" property="maxLoginTime" jdbcType="TIMESTAMP" />
  11. </resultMap>
  12. <!-- 根据用户ID集合查询出用户最近登录时间 -->
  13. <select id="selectUserMaxLoginTimeByUserIds" parameterType="map" resultMap="MaxLoginTimeMap">
  14. SELECT
  15. USER_ID as userId ,
  16. MAX(LOGIN_TIME) as maxLoginTime
  17. FROM
  18. user_login_details
  19. WHERE
  20. USER_ID IN
  21. <foreach collection="list" item="userId" index="index" open="("
  22. close=")" separator=",">
  23. #{userId}
  24. </foreach>
  25. group by USER_ID
  26. ORDER BY USER_ID ASC
  27. </select>

得到insert后的自增长ID

  1. 调用:(count为影响条数,replyid字段在添加之后会有值---自增长ID)
  2. int count = this.mapperFactory.replyMapper.insertSelective(reply);
  3. //mapper.java
  4. public abstract int insert(Reply paramReply);
  5. <insert id="insert" parameterType="com.clou.douliu.server.bean.mybatis.Reply" >
  6. <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
  7. SELECT LAST_INSERT_ID()
  8. </selectKey>
  9. insert into comment (USER_ID, CONTENT, PICTURE,
  10. TIMETAG, TYPE, ACT_ID,
  11. VALID)
  12. values (#{userId,jdbcType=INTEGER}, #{content,jdbcType=VARCHAR},
  13. #{picture,jdbcType=VARCHAR,javaType=String,
  14. typeHandler=com.clou.douliu.server.mybatis.plugin.RemoveDomainTypeHandler},
  15. #{timetag,jdbcType=TIMESTAMP}, #{type,jdbcType=INTEGER},#{actId,jdbcType=INTEGER},
  16. #{valid,jdbcType=SMALLINT})
  17. </insert>

排除(筛选热门分享,排除管理员1号)

  1. <!-- 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. -->
  2. <select id="selectHotShareAlternativeListByUserId" parameterType="map" resultMap="ShareDetailMap">
  3. SELECT * FROM
  4. (SELECT
  5. <include refid="Alias_Column_List" />,
  6. <include refid="com.clou.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />,
  7. <include refid="com.clou.douliu.server.mybatis.mapper.UserDetailsMapper.Alias_Column_List"/>
  8. FROM
  9. ACTIVITYS ACTIVITYS
  10. left join USER USER on (USER.ID=ACTIVITYS.USER_ID)
  11. left join user_details user_details ON (user_details.USER_ID = USER.ID)
  12. WHERE
  13. USER.TYPE > 0
  14. AND USER.ID = #{userId,jdbcType=INTEGER}
  15. AND ACTIVITYS.valid = 1
  16. AND ACTIVITYS.timetag >= #{startDate,jdbcType=TIMESTAMP}
  17. AND ACTIVITYS.timetag <= date_add(#{endDate,jdbcType=TIMESTAMP},interval 24 hour)
  18. ORDER BY date(ACTIVITYS.timetag) desc
  19. LIMIT #{start,jdbcType=INTEGER},#{loadSize,jdbcType=INTEGER}) TEMP
  20. WHERE
  21. NOT EXISTS(SELECT 1 FROM HOTS HOTS WHERE HOTS.ACT_ID = TEMP.ACTIVITYS_ID)
  22. </select>

list参数传递

  1. /**
  2. * 通过id集合删除记录
  3. * @param delPhotoIdList id集合
  4. * @return
  5. */
  6. public abstract int removeByIdList(List<Integer> delPhotoIdList);
  7. <!-- 通过id集合删除记录 -->
  8. <delete id="removeByIdList">
  9. delete from album_detail where ID in
  10. <foreach collection="list" item="photoId" index="index"
  11. open="(" close=")" separator=",">
  12. #{photoId}
  13. </foreach>
  14. </delete>

Map参数传递(find_in_set用法)

  1. /**
  2. * 根据群id集合获取群的全部信息,按照list里面的序号排序
  3. * @param paramMap 参数map <br/>
  4. * groupIdList --- List<Integer> <br/>
  5. * sortStr ---- String 排序字符串,格式:'1932,2342,3242' 也就是集合中的id,已逗号隔开
  6. */
  7. List<Groups> selectGroupListBySort(Map<String, Object> paramMap);
  8. <!-- 根据群id集合获取群的全部信息,按照list里面的序号排序 -->
  9. <select id="selectGroupListBySort" resultMap="BaseResultMap" parameterType="java.util.Map" >
  10. select
  11. <include refid="Base_Column_List" />
  12. from groups
  13. where id in
  14. <foreach collection="groupIdList" item="item" index="index" open="(" close=")" separator=",">
  15. #{item}
  16. </foreach>
  17. and status = 1
  18. order by find_in_set(id, #{sortStr,jdbcType=VARCHAR}) asc;
  19. </select>
  20. Bussiness方法:从redis中取出热门群组列表,按照指定顺序从数据库中查询详细信息
  21. /**
  22. * 获取推荐群列表
  23. * @return
  24. */
  25. public List<Groups> selectTopGroups() {
  26. CacheManager cm=CacheManager.getInstance();
  27. Set<String> s=cm.getRecommandGroups();
  28. logger.debug("推荐列表" + s);
  29. List<Integer> groupIds = null;
  30. if(s!=null && s.size() > 0){
  31. groupIds = new ArrayList<Integer>();
  32. for(String g : s){
  33. try {
  34. Integer gId = Integer.parseInt(g);
  35. groupIds.add(gId);
  36. } catch (Exception e) {
  37. }
  38. }
  39. }
  40. if(groupIds != null && groupIds.size() > 0){
  41. Map<String, Object> paramMap = new HashMap<String, Object>();
  42. StringBuilder sortStr = new StringBuilder();
  43. for(Integer id : groupIds){
  44. sortStr.append(id).append(",");
  45. }
  46. sortStr.delete(sortStr.lastIndexOf(","), sortStr.length());
  47. paramMap.put("groupIdList", groupIds);
  48. paramMap.put("sortStr", sortStr.toString());
  49. return this.mapperFactory.groupsMapper.selectGroupListBySort(paramMap);
  50. }
  51. return null;
  52. }

Criteria的Where条件拼凑(工具自动生成)

1、不带别名的写法,用于单张表的操作

  1. <sql id="Example_Where_Clause" >
  2. <where >
  3. <foreach collection="oredCriteria" item="criteria" separator="or" >
  4. <if test="criteria.valid" >
  5. <trim prefix="(" suffix=")" prefixOverrides="and" >
  6. <foreach collection="criteria.criteria" item="criterion" >
  7. <choose >
  8. <when test="criterion.noValue" >
  9. and ${criterion.condition}
  10. </when>
  11. <when test="criterion.singleValue" >
  12. and ${criterion.condition} #{criterion.value}
  13. </when>
  14. <when test="criterion.betweenValue" >
  15. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  16. </when>
  17. <when test="criterion.listValue" >
  18. and ${criterion.condition}
  19. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  20. #{listItem}
  21. </foreach>
  22. </when>
  23. </choose>
  24. </foreach>
  25. </trim>
  26. </if>
  27. </foreach>
  28. </where>
  29. </sql>
  30. 例子:
  31. List<PushSchema> selectByExample(PushSchemaCriteria example) throws RuntimeException;
  32. <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.clou.douliu.server.bean.mybatis.PushSchemaCriteria" >
  33. select
  34. <if test="distinct" >
  35. distinct
  36. </if>
  37. <include refid="Base_Column_List" />
  38. from push_schema
  39. <if test="_parameter != null" >
  40. <include refid="Example_Where_Clause" />
  41. </if>
  42. <if test="orderByClause != null" >
  43. order by ${orderByClause}
  44. </if>
  45. <if test="start >= 0 " >
  46. limit ${start}
  47. </if>
  48. <if test="count >= 0 " >
  49. ,${count}
  50. </if>
  51. </select>

带别名的写法,用于多张表联合操作

  1. <sql id="Alias_Update_By_Example_Where_Clause" >
  2. <where >
  3. <foreach collection="example.oredCriteria" item="criteria" separator="or" >
  4. <if test="criteria.valid" >
  5. <trim prefix="(" suffix=")" prefixOverrides="and" >
  6. <foreach collection="criteria.criteria" item="criterion" >
  7. <choose >
  8. <when test="criterion.noValue" >
  9. and PUSH_SCHEMA.${criterion.condition}
  10. </when>
  11. <when test="criterion.singleValue" >
  12. and PUSH_SCHEMA.${criterion.condition} #{criterion.value}
  13. </when>
  14. <when test="criterion.betweenValue" >
  15. and PUSH_SCHEMA.${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  16. </when>
  17. <when test="criterion.listValue" >
  18. and PUSH_SCHEMA.${criterion.condition}
  19. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  20. #{listItem}
  21. </foreach>
  22. </when>
  23. </choose>
  24. </foreach>
  25. </trim>
  26. </if>
  27. </foreach>
  28. </where>
  29. </sql>
  30. 例子:
  31. /**
  32. * 查询方案列表(包含具体方案step的List)
  33. * @param example
  34. * @return
  35. * @throws RuntimeException
  36. */
  37. List<PushSchema> selectWithStepByExample(PushSchemaCriteria example) throws RuntimeException;
  38. <!-- 查询方案列表(关联查询具体方案) -->
  39. <select id="selectWithStepByExample" resultMap="SchemaWithStepMap" parameterType="com.clou.douliu.server.bean.mybatis.PushSchemaCriteria" >
  40. select
  41. <include refid="Alias_Column_List" />,
  42. <include refid="com.clou.douliu.server.mybatis.mapper.PushStepMapper.Alias_Column_List" />
  43. from push_schema PUSH_SCHEMA
  44. left join push_step PUSH_STEP on (PUSH_SCHEMA.ID=PUSH_STEP.SCHEMA_ID)
  45. <if test="_parameter != null" >
  46. <include refid="Alias_Example_Where_Clause" />
  47. </if>
  48. <if test="orderByClause != null" >
  49. order by ${orderByClause}
  50. </if>
  51. <if test="start >= 0 " >
  52. limit ${start}
  53. </if>
  54. <if test="count >= 0 " >
  55. ,${count}
  56. </if>
  57. </select>

3、复杂条件筛选

刚刚这个例子,只是针对与Push_Schma表有筛选条件,如果Push_step表也有条件,那么条件语句就要改写了

原理:

先有where语句,再把Criteria的条件拼凑到后面,

这就涉及到Criteria条件到底存不存在的问题,存在才有and ,不存在就直接结束


AND

暂时没有研究传递两个参数(PushSchemaCriteria, PushStepCriteria)的形式

有改写了where条件的写法,详细请看下一个案例。

Collection 和 association 的用法

  1. /**
  2. * selectShareDetailList: 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. <br/>
  3. *
  4. *
  5. * @author Hongbin Yuan
  6. * @param bean
  7. * @return
  8. * @since JDK 1.6
  9. */
  10. public abstract List<Share> selectShareDetailList(ShareCriteria paramShareCriteria);
  11. <!-- 分享列表,包含发布分享的人,以及该分享对应的图片列表 -->
  12. <resultMap id="ShareDetailMap" type="com.clou.douliu.server.bean.mybatis.Share" extends="AliasResultMap">
  13. <association property="publisher"
  14. resultMap="com.clou.douliu.server.mybatis.mapper.UserMapper.UserDetailResultMap"></association>
  15. <collection property="sharePictureList" resultMap="com.clou.douliu.server.mybatis.mapper.SharePictureMapper.AliasResultMap"></collection>
  16. </resultMap>
  17. <!-- 选取分享列表,包含发布分享的人,以及该分享对应的图片列表. -->
  18. <select id="selectShareDetailList" parameterType="com.clou.douliu.server.bean.mybatis.ShareCriteria" resultMap="ShareDetailMap">
  19. SELECT
  20. <include refid="Alias_Column_List" />,
  21. <include
  22. refid="com.clou.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />,
  23. <include
  24. refid="com.clou.douliu.server.mybatis.mapper.SharePictureMapper.Alias_Column_List" />
  25. FROM
  26. ACTIVITYS ACTIVITYS
  27. left join USER USER on (USER.ID=ACTIVITYS.USER_ID)
  28. left join ACT_PICTURE ACT_PICTURE on (ACTIVITYS.ID=ACT_PICTURE.ACT_ID)
  29. WHERE
  30. USER.type > 0
  31. <foreach collection="oredCriteria" item="criteria" index="index" separator="or">
  32. <if test="criteria.valid" >
  33. <if test="index == 0">
  34. AND
  35. </if>
  36. <trim prefix="(" suffix=")" prefixOverrides="and">
  37. <foreach collection="criteria.criteria" item="criterion">
  38. <choose>
  39. <when test="criterion.noValue">
  40. and ACTIVITYS.${criterion.condition}
  41. </when>
  42. <when test="criterion.singleValue">
  43. and ACTIVITYS.${criterion.condition} #{criterion.value}
  44. </when>
  45. <when test="criterion.betweenValue">
  46. and ACTIVITYS.${criterion.condition} #{criterion.value} and
  47. #{criterion.secondValue}
  48. </when>
  49. <when test="criterion.listValue">
  50. and ACTIVITYS.${criterion.condition}
  51. <foreach collection="criterion.value" item="listItem"
  52. open="(" close=")" separator=",">
  53. #{listItem}
  54. </foreach>
  55. </when>
  56. </choose>
  57. </foreach>
  58. </trim>
  59. </if>
  60. </foreach>
  61. <if test="orderByClause != null">
  62. order by ${orderByClause}
  63. </if>
  64. <if test="start >= 0 ">
  65. limit ${start}
  66. </if>
  67. <if test="end >= 0 ">
  68. ,${end}
  69. </if>
  70. </select>

日期操作,choose语法,分页做法

  1. /**
  2. * selectCommonShareList:查询分享列表,包含分享人的信息 <br/>
  3. * @author dhh
  4. * @param userId 查询指定用户的分享
  5. * @param daysBeforeToday 默认查询多少天之内的分享
  6. * @param lastShareId 页面加载时,查询的上一条分享的id
  7. * @param loadSize 每次加载的分享数量
  8. * @return
  9. * @since JDK 1.6
  10. */
  11. public abstract List<Share> selectCommonShareList(
  12. @Param("userId") Integer userId,
  13. @Param("daysBeforeToday") Integer daysBeforeToday,
  14. @Param("lastShareId") Integer lastShareId,
  15. @Param("loadSize") Integer loadSize);
  16. <!-- 查询普通分享 -->
  17. <resultMap id="SharePublisherMap" type="com.clou.douliu.server.bean.mybatis.Share" extends="AliasResultMap">
  18. <association property="publisher"
  19. resultMap="com.clou.douliu.server.mybatis.mapper.UserMapper.AliasResultMap">
  20. </association>
  21. </resultMap>
  22. <!-- 查询普通分享 -->
  23. <select id="selectCommonShareList" parameterType="map" resultMap="SharePublisherMap">
  24. SELECT
  25. <include refid="Alias_Column_List" />,
  26. <include refid="com.douliu.server.mybatis.mapper.UserMapper.Alias_Column_List" />
  27. FROM
  28. USER USER,
  29. ACTIVITYS ACTIVITYS
  30. WHERE
  31. USER.ID=ACTIVITYS.USER_ID
  32. AND ACTIVITYS.TYPE = 5
  33. AND USER.TYPE > 0
  34. AND ACTIVITYS.VALID > -1
  35. <if test="userId != null and userId >0">
  36. AND USER.ID = #{userId,jdbcType=INTEGER}
  37. </if>
  38. AND ACTIVITYS.TIMETAG > DATE_ADD(CURDATE(),INTERVAL -
  39. <choose>
  40. <when test="daysBeforeToday != null and daysBeforeToday > 0">
  41. #{daysBeforeToday}
  42. </when>
  43. <otherwise>
  44. 7
  45. </otherwise>
  46. </choose>
  47. DAY)
  48. <if test="lastShareId != null">
  49. AND ACTIVITYS.ID < #{lastShareId}
  50. </if>
  51. ORDER BY
  52. ACTIVITYS.ID DESC
  53. LIMIT 0 ,
  54. <choose>
  55. <when test="loadSize != null and loadSize > 0">
  56. #{loadSize}
  57. </when>
  58. <otherwise>
  59. 10
  60. </otherwise>
  61. </choose>
  62. </select>

☞分页查询一个注意点:如果想分页查出的数据不出现重复(app有新增),最后记录上一次查询的最大值,然后在分页查询的时候 id>最大值 limit (也可以传最小值,不过客户端要每次维护这个值,但是如果存最大值,就第一次维护就行了)

Collection附加一种写法:

Center

Center 1

不推荐使用,只是语法是这样,之前做举报功能列表,而一个聊天举报可能对应很多条聊天信息,用这种方法查询,结果很慢,后来先查出列表,取出ID列表,然后in(ids) 查询聊天记录,然后for循坏加到对应的id,再set进去,效率反而快一些。

发表评论

表情:
评论列表 (有 0 条评论,515人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jsp分页的写法

    这里运用mvc格式去写分页,期间会用到jstl标签,c3p0连接池,jdbc数据库连接,tomcat服务器,以及可以先把包导入到项目中,具体的导包过程可以百度。 ![在这里