当前位置:   article > 正文

MyBatis语法(一)总述_com.iflytek

com.iflytek

一、简介

1、介绍

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。

MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

Mybatis框架的组成架构图如下:

如图所见我们把Mybatis的功能架构分为四层:
1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。

2)数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。

3)基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。

4)引导层:基于XML配置方式还是基于Java API方式。

MyBatis 支持延迟加载,设置 lazyLoadingEnabled=true 即可。

2、MyBatis 有三种基本的Executor执行器:

SimpleExecutor:每执行一次 update 或 select 就开启一个 Statement 对象,用完立刻关闭 Statement 对象;
ReuseExecutor:执行 update 或 select,以 SQL 作为 key 查找 Statement 对象,存在就使用,不存在就创建,用完后不关闭 Statement 对象,而是放置于 Map 内供下一次使用。简言之,就是重复使用 Statement 对象;
BatchExecutor:执行 update(没有 select,jdbc 批处理不支持 select),将所有 SQL 都添加到批处理中(addBatch()),等待统一执行(executeBatch()),它缓存了多个 Statement 对象,每个 Statement 对象都是 addBatch()完毕后,等待逐一执行 executeBatch()批处理,与 jdbc 批处理相同。

二、关键字符:

1、我们需要通过xml格式处理sql语句时,经常会用到< ,<=,>,>=等符号,但是很容易引起xml格式的错误,这样会导致后台将xml字符串转换为xml文档时报错,从而导致程序错误。

  这样的问题在iBatiS中或者自定义的xml处理sql的程序中经常需要我们来处理。其实很简单,我们只需作如下替换即可避免上述的错误:

2、#相当于对数据 加上 双引号;$相当于直接显示数据,不会加上引号:

  1. public List<GroupUsersProfile> queryGroupUsers(QueryGroupUsersModel queryGroupUsersModel) {
  2. //crowdId非空
  3. if(StringUtils.isEmpty(queryGroupUsersModel.getCrowdId())==true) {
  4. new ArrayList<GroupUsersProfile>();
  5. }
  6. //需要part
  7. if(StringUtils.isEmpty(queryGroupUsersModel.getPart())==true) {
  8. UserGroup userGroup = userGroupService.queryUserGroupById(queryGroupUsersModel.getCrowdId());
  9. if(userGroup!=null) {
  10. queryGroupUsersModel.setPart(userGroup.getPart());
  11. }
  12. }
  13. //查询表名
  14. String tableName = cmsCrowdRouteMapper.getCrowdTableByCrowdId(queryGroupUsersModel.getCrowdId());
  15. if(tableName==null) {
  16. logger.error("%s查看人群用户列表,获取tableName空,crowdId:%s",null,queryGroupUsersModel.getCrowdId());
  17. return null;
  18. }
  19. //查询数目
  20. if(queryGroupUsersModel.getStartIndex() == null) {
  21. queryGroupUsersModel.setStartIndex(0);
  22. }
  23. if(queryGroupUsersModel.getPageSize() == null || queryGroupUsersModel.getPageSize().intValue() <=0) {
  24. queryGroupUsersModel.setPageSize(10);
  25. }
  26. //mysql查询
  27. return groupUsersMapper.getGroupUsersList(queryGroupUsersModel);
  28. }
  1. <!--查询用户群用户-->
  2. <select id="getGroupUsersList" resultMap="BaseResultMap" parameterType="com.iflytek.edmp.domain.vo.QueryGroupUsersModel">
  3. select
  4. <include refid="Base_Column_List" />
  5. from ${tableName}
  6. WHERE
  7. 1=1
  8. and is_delete = 0
  9. <if test=" crowdId != null and crowdId != ''">
  10. and crowd_id = #{crowdId,jdbcType=VARCHAR}
  11. </if>
  12. <if test=" part != null and part != ''">
  13. and part = #{part,jdbcType=VARCHAR}
  14. </if>
  15. <if test=" orderColumn != null and orderColumn != '' and orderDir != null and order !=''">
  16. ORDER BY ${orderColumn} ${orderDir}
  17. </if>
  18. <if test=" startIndex != null and startIndex != '' and pageSize != null and pageSize != ''">
  19. LIMIT #{startIndex},#{pageSize}
  20. </if>
  21. </select>

在使用 #{}时,MyBatis 会将 SQL 中的 #{}替换成“?”,配合 PreparedStatement 的 set 方法赋值,这样可以有效的防止 SQL 注入,保证程序的运行安全。 

三、传参:一般有两种方法:

1、在dao.java的接口上给参数加上@Param注解,sql中不需要再写parameterType,直接使用即可;如:

UserDao.java:

int insert(@Param("user") User user,@Param("userId") String userId);

xml:

  1. <insert id="insert">
  2. insert into user values(#{user.userName},#{userId})
  3. </insert>

2、在dao.java的接口参数上不加@Param注解,sql中需要写parameterType指明类型。

四、基础持久化操作:增删改可以不返回结果,查询必须返回结果,也即必须有resultType或者resultMap。

1、增(insert):

下面在com.iflytek.dao下创建两个文件来进行数据库操作:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.iflytek.dao.BlogMapper">
  6. <insert id="addBlog" parameterType="Blog">
  7. insert into t_blog
  8. (id, title)
  9. values
  10. (#{id}, #{title})
  11. </insert>
  12. </mapper>

已定义的类型用parameterType。

  1. package com.iflytek.dao;
  2. import com.iflytek.domain.Blog;
  3. public interface BlogMapper {
  4. public void addBlog(Blog blog);
  5. }

测试:

  1. package com.iflytek.test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import com.iflytek.dao.BlogMapper;
  9. import com.iflytek.domain.Blog;
  10. import oracle.net.aso.b;
  11. public class Main {
  12. public static void main(String[] args) throws Exception {
  13. String resource = "mybatis-config.xml";
  14. InputStream inputStream = Resources.getResourceAsStream(resource);
  15. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  16. SqlSession session = sqlSessionFactory.openSession();
  17. try {
  18. BlogMapper mapper = session.getMapper(BlogMapper.class);
  19. Blog blog=new Blog();
  20. blog.setId(3);
  21. blog.setTitle("第三篇");
  22. //blog.setAuthor(1);
  23. mapper.addBlog(blog);
  24. session.commit();
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }

2、删(delete):

  1. <delete id="deleteBlog" parameterType="Blog">
  2. delete from t_blog where title=#{title}
  3. </delete>
public void deleteBlog(Blog blog);

测试:

  1. String resource = "mybatis-config.xml";
  2. InputStream inputStream = Resources.getResourceAsStream(resource);
  3. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  4. SqlSession session = sqlSessionFactory.openSession();
  5. try {
  6. BlogMapper mapper = session.getMapper(BlogMapper.class);
  7. Blog blog=new Blog();
  8. //blog.setId(3);
  9. blog.setTitle("第三篇");
  10. //blog.setAuthor(1);
  11. mapper.deleteBlog(blog);
  12. session.commit();
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }

3、改(update):

public int updateEmp(Emp emp);
  1. <update id="updateEmp" parameterType="Emp" >
  2. update emp set money=#{money} where id=#{id}
  3. </update>

4、查(select):

五、复杂操作:

1、嵌套查询:一对一用association,一对多用collection:

  例1:

  1. public Blog selectBlog(int id);
  1. <resultMap type="Blog" id="blogres">
  2. <id property="id" column="bid" ></id>
  3. <result property="title" column="title"/>
  4. <association property="author" javaType="Author">
  5. <id property="id" column="aid"></id>
  6. <result property="name" column="aname"/>
  7. </association>
  8. <collection property="posts" ofType="Post">
  9. <id property="id" column="pid"/>
  10. <result property="name" column="name"/>
  11. </collection>
  12. </resultMap>
  13. <select id="selectBlog" parameterType="int" resultMap="blogres">
  14. select b.id as bid,
  15. b.title,
  16. a.id as aid,
  17. a.name as aname,
  18. p.id as pid,
  19. p.name
  20. from t_blog b
  21. left join author a on b.authorid = a.id
  22. left join post p on p.bid = b.id where b.id = #{id}
  23. </select>

  引用自定义的用resultMap。

测试:

  1. BlogMapper mapper = session.getMapper(BlogMapper.class);
  2. Blog b = mapper.selectBlog(1);
  3. System.out.println(b);

例2:

  1. public class UserInfoVO implements Serializable {
  2. private String userId;
  3. private String userAccount;
  4. private String userName;
  5. private RoleInfo roleInfo;
  6. }
  7. public class RoleInfo implements Serializable {
  8. private Integer roleId;
  9. private String roleName;
  10. private String roleCode;
  11. private Integer roleType;
  12. private List<ProvinceSchoolInfo> provinceSchoolQInfos = new ArrayList<>();
  13. }
  14. public class ProvinceSchoolInfo implements Serializable {
  15. private List<ProvinceInfo> provinceInfos = new ArrayList<>();
  16. }
  17. public class ProvinceInfo implements Serializable {
  18. private Long provinceId;
  19. private String provinceName;
  20. private List<CityInfo> cityInfos = new ArrayList<>();
  21. }
  22. public class CityInfo implements Serializable {
  23. private Long cityId;
  24. private String cityName;
  25. private List<DistrictInfo> districtInfos = new ArrayList<>();
  26. }
  27. public class DistrictInfo implements Serializable {
  28. private Long districtId;
  29. private String districtName;
  30. }

对应的map:

  1. <resultMap id="UserInfoVOMap" type="com.demo.business.vo.dbo.UserInfoVO">
  2. <result column="USER_ID" jdbcType="VARCHAR" property="userId" />
  3. <association property="roleInfo" javaType="com.demo.business.permission.vo.RoleInfo">
  4. <result column="ROLE_ID" jdbcType="INTEGER" property="roleId" />
  5. <collection property="provinceSchoolQInfos" ofType="com.demo.business.permission.vo.ProvinceSchoolInfo">
  6. <collection property="provinceInfos" ofType="com.demo.business.permission.vo.ProvinceInfo">
  7. <result column="PROVINCE_ID" jdbcType="BIGINT" property="provinceId" />
  8. <result column="province_name" jdbcType="VARCHAR" property="provinceName" />
  9. <collection property="cityInfos" ofType="com.demo.business.permission.vo.CityInfo">
  10. <result column="CITY_ID" jdbcType="BIGINT" property="cityId" />
  11. <result column="city_name" jdbcType="INTEGER" property="cityName" />
  12. <collection property="districtInfos" ofType="com.demo.business.permission.vo.DistrictInfo">
  13. <result column="DISTRICT_ID" jdbcType="BIGINT" property="districtId" />
  14. <result column="district_name" jdbcType="VARCHAR" property="districtName" />
  15. </collection>
  16. </collection>
  17. </collection>
  18. </collection>
  19. </association>
  20. </resultMap>

注意:在使用mybatis时,集合标签<collection>可以帮我们实现聚合功能,但是会对聚合到的数据进行自动去重,也即对collection标签内的整体进行去重,所以如果不想去重,需要加一个唯一标志性的字段,如我查询学生考试列表,

  1. <collection property="exmas" ofType="com.demo.Exam">
  2. <result column="examName" jdbcType="VARCHAR" property="examName" />
  3. </collection>

这样结果会去重,如语文、数学、英语,如果我希望查询学生历史考试情况(不需要按照考试科目名称去重)可以加个主键,将聚合目标字段+主键id字段封装为一个对象UID

  1. <collection property="exmas" ofType="com.demo.Exam">
  2. <id property="id" column="id"/>
  3. <result column="examName" jdbcType="VARCHAR" property="examName" />
  4. </collection>

2、批量插入:注意foreach语句不需要括号:

  1. <!--批量插入用户权限-->
  2. <insert id="updateUserRoles" >
  3. insert into userrole (rid,uid)
  4. values
  5. <foreach collection="rlist" item="item" index="index" separator=",">(#{item},#{uid})</foreach>
  6. </insert>
 int insertUserChannel(@Param("uid") String uid,@Param("list") List<HashMap<String,String>> channelMap);
  1. <!--批量插入-->
  2. <insert id="insertUserChannel">
  3. insert into user_channel_relation ( relation_id, user_group_id, channel_id, enable_flag)
  4. values
  5. <foreach collection="list" item="item" index="index" separator=",">
  6. (#{item.id},#{uid},#{item.channelId},#{item.flag})</foreach>
  7. </insert>

3、批量更新:注意需要在数据库连接处开启批量更新

&allowMultiQueries=true

语法同批量插入

  1. int updateUserRoles(@Param("uid")String uid, @Param("rlist")List<String> ridList);
  1. void updateUserBatch(@Param(value = "userList") List<User> userList, @Param(value = "tableName") String tableName);
  2. <update id="updateUserBatch">
  3. <foreach collection="userList" item="user" separator=";" index="index">
  4. update ${tableName}
  5. <set>
  6. user_name = #{user.userName}
  7. </set>
  8. <where>
  9. user_id = #{user.userId}
  10. </where>
  11. </foreach>
  12. </update>

4、批量删除:

  1. <delete id="batchDelete" parameterType="java.util.List">
  2. DELETE FROM table_name WHERE column_id IN
  3. <foreach collection="list" item="item" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </delete>

 5、in查询:注意foreach语句需要括号:

List<DeliveryRule> selectListByPositionCodeAndTag(@Param("positionCode") String positionCode, @Param("tags")Set<String> tags);
  1. <select id="selectListByPositionCodeAndTag" resultMap="BaseResultMap">
  2. select
  3. <include refid="User_Column_List"/>
  4. from cia_delivery_rule
  5. where resource_position_code = #{positionCode,jdbcType=VARCHAR}
  6. and tag_value IN
  7. <foreach collection="tags" index="index" item="item" open="(" separator="," close=")">
  8. #{item}
  9. </foreach>
  10. and `status` = 10
  11. and start_time < NOW() and end_time > NOW()
  12. </select>

6、模糊查询:

(1)基础写法:用$,而不用#

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.iflytek.dao.GoodsMapper">
  6. <select id="getGoods" resultType="Goodsinfo" parameterType="Goodcategory">
  7. select * from goodsinfo i
  8. left join goodcategory c
  9. on i.cid=c.id where c.title like '%${title}%'
  10. and c.pid!=0
  11. </select>
  12. </mapper>

(2)安全写法:实际应用中,上述的模糊匹配是有SQL注入风险的,需要like CONCAT(CONCAT('%',#{title}),'%');且一般为了命中索引使用后模糊:

user_account like CONCAT(CONCAT(#{query.userAccount}),'%')

六、动态sql:mybatis提供了丰富的标签库支持动态SQL,可以像写java代码那样写sql语句:

例1:

  1. <select id="select" parameterType="Blog" resultType="Blog">
  2. select * from t_blog where 1=1
  3. <if test="id!=null">
  4. and id=#{id}
  5. </if>
  6. </select>
public List<Blog> select(Blog blog);

测试:

  1. BlogMapper mapper = session.getMapper(BlogMapper.class);
  2. Blog blog=new Blog();
  3. List<Blog> b = mapper.select(blog);
  4. System.out.println(b);

  1. BlogMapper mapper = session.getMapper(BlogMapper.class);
  2. Blog blog=new Blog();
  3. blog.setId(1);
  4. List<Blog> b = mapper.select(blog);
  5. System.out.println(b);

 这个例子需要注意一下,判断的条件是id==null,所以Blog的id字段设的是Integer而不是int,因为基本类型默认是有初始值的,如int初始值为0,可是数据库中却可以存在id为0的数据,而引用类型初始值为null,因为数据库中不可能存在为null的字段,这样就好判断一点。

例2:根据角色id、省市区id(空或-1则为全部)查询重复用户:

  1. <!--根据角色、区域查询重复用户-->
  2. <select id="getByAreaAndRole" resultMap="UserInfoVOMap">
  3. select
  4. t.USER_ID USER_ID,
  5. t.ROLE_ID ROLE_ID,
  6. t.PROVINCE_ID PROVINCE_ID,
  7. t.CITY_ID CITY_ID,
  8. t.DISTRICT_ID DISTRICT_ID,
  9. p.province_name province_name,
  10. c.city_name city_name,
  11. d.district_name district_name
  12. from T_USER_ROLE_AREA t
  13. LEFT JOIN dw.dw_province_dim p ON t.PROVINCE_ID = p.province_id
  14. LEFT JOIN dw.dw_city_dim c ON t.CITY_ID = c.city_id
  15. LEFT JOIN dw.dw_district_dim d ON t.DISTRICT_ID = d.district_id
  16. where t.is_delete = 0
  17. and t.ROLE_ID = #{roleId}
  18. and t.USER_ID!=#{userId}
  19. <if test="provinceInfos.size > 0">
  20. and
  21. <foreach collection="provinceInfos" item="provinceInfo" open="(" close=")" separator="or">
  22. <choose>
  23. <when test="provinceInfo.provinceId != null ">
  24. (t.PROVINCE_ID = #{provinceInfo.provinceId} or t.PROVINCE_ID = -1 )
  25. </when>
  26. <otherwise> 1 = 1 </otherwise>
  27. </choose>
  28. <if test="provinceInfo.cityInfos.size > 0">
  29. and
  30. <foreach collection="provinceInfo.cityInfos" item="cityInfo" open="(" close=")" separator="or">
  31. <choose>
  32. <when test="cityInfo.cityId != null">
  33. (t.CITY_ID = #{cityInfo.cityId} or t.CITY_ID = -1 or t.CITY_ID is null)
  34. </when>
  35. <otherwise>1=1</otherwise>
  36. </choose>
  37. <if test="cityInfo.districtInfos.size > 0">
  38. and
  39. <foreach collection="cityInfo.districtInfos" item="districtInfo" open="(" close=")" separator="or">
  40. <choose>
  41. <when test="districtInfo.districtId !=null">
  42. (t.DISTRICT_ID = #{districtInfo.districtId} or t.DISTRICT_ID = -1 or t.DISTRICT_ID is null)
  43. </when>
  44. <otherwise>1=1</otherwise>
  45. </choose>
  46. </foreach>
  47. </if>
  48. </foreach>
  49. </if>
  50. </foreach>
  51. </if>
  52. </select>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/225400
推荐阅读
相关标签
  

闽ICP备14008679号