MyBatis快速入门

MyBatis

快速入门

  1. 创建xml文件:mybatis-config.xml

  2. 配置

    java 复制代码
     <?xml version="1.0" encoding="UTF-8" ?>
     <!DOCTYPE configuration
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
     <configuration>
       <environments default="development">
         <environment id="development">
           <transactionManager type="JDBC"/>
           <dataSource type="POOLED">
             <property name="driver" value="${driver}"/>
             <property name="url" value="${url}"/>
             <property name="username" value="${username}"/>
             <property name="password" value="${password}"/>
           </dataSource>
         </environment>
       </environments>
       <mappers>
         <mapper resource="org/mybatis/example/BlogMapper.xml"/>
       </mappers>
     </configuration>
  3. 创建xml文件,namespace作用域,id唯一标识符,传入sqlSession的方法中执行

    java 复制代码
     <?xml version="1.0" encoding="UTF-8" ?>
     <!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     <mapper namespace="org.mybatis.example.BlogMapper">
       <select id="selectBlog" resultType="Blog">
         select * from Blog where id = #{id}
       </select>
     </mapper>
  4. 创建SqlSessionFactory以及SqlSession

    java 复制代码
     String resource = "org/mybatis/example/mybatis-config.xml";
     InputStream inputStream = Resources.getResourceAsStream(resource);
     SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
     ​
     SqlSession sqlSession = sqlSessionFactory.openSession();
     //硬编码问题,下一节解决
     sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
     sqlSession.selectList();                                                                      
     sqlSession.close();                                                                 

Mapper代理开发

  1. 定义Mapper接口:xml文件要和接口在同一目录下,例如resources创建top/zendee/mapper

  2. 命名空间改为Mapper接口

    java 复制代码
     <!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     <mapper namespace="top.zendee.mapper.UserMapper">
       <select id="selectBlog" resultType="Blog">
         select * from Blog where id = #{id}
       </select>
     </mapper>
  3. 映射文件的id方法名 相同,返回值相同

  4. 使用接口

    java 复制代码
     BlogMapper mapper = session.getMapper(BlogMapper.class);
     Blog blog = mapper.selectBlog(101);

MyBatisX插件

  • 功能:XML接口方法 相互跳转,根据接口方法生成statement

字段映射

  • 起别名:在xml文件的sql语句中给列起别名,例如brand_name as brandName。

  • sql片段:

    java 复制代码
     <sql id = user>`
     id , user_name as userName, phone, email`
     </sql>
     ​
     <select id = selectAll resultType = "user">
         select
             <include refid="user"/>
         from user;
     </select>
  • resultMap映射:id :主键,result:一般列。

    java 复制代码
     <resultMap type="User" id="userResultMap">
         <id property="userId" column="user_id" javaType="int" jdbcType="int"/>
         <result property="name" column="name" javaType="String" jdbcType="VARCHAR"/>
     </resultMap>
     //也可如下:
     <resultMap type="User" id="userResultMap">
         //主键字段映射
         <id property="userId" column="user_id"/>
         //一般字段映射
         <result property="name" column="name"/>
     </resultMap>
         
     //同时修改resultType -> resultMap
     <select id = selectAll resultMap = "userResultMap">
         select *
         from user;
     </select>

查询

  • 查询所有数据
  • 产看单个数据
java 复制代码
 <!DOCTYPE mapper
   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="top.zendee.mapper.UserMapper">
     
     <resultMap id="userResultMap" type="top.zendee.entity.User">
         <id column="user_id" property="userId">
         <result column="user_name" property="userName">
     </resultMap>
     
     //$存在sql注入问题,在表名或者列名不确定可以使用
     <select id="selectUserById" resultMap="userResultMap">
         select * from user where user_id = #{id}
     </select>
 </mapper>
  • 多重判断模糊查询
java 复制代码
//mapper接口
List<Brand> selectByCondition(@Param("status")int status, @Param("brandName")String brandName);
//或者
List<Brand> selectByCondition(Brand brand);
//或者
List<Brand> selectByCondition(Map map);

//XML文件,模糊查询%和_,在java函数中进行处理,例如华为->%华为%
<select id="selectByCondition" resultMap="brandResultMap">
    select * from brand
    where 
    	status like #{status}
		and brand_name like #{brandName}
</select>

特殊字符处理

  • 转义字符:&lt,例如&lt <(小于)
  • <! [CDATA[ 特殊字符 ]]>:例如<! [CDATA[ <(小于) ]]>

动态查询

  • if
java 复制代码
<select id="findActiveBlogWithTitleLike" resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = 'ACTIVE'
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
      
<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = 'ACTIVE'
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
  • choose-when-otherwise
java 复制代码
//只匹配一个条件。类似switch语句
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = 'ACTIVE'
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND 1 = 1
    </otherwise>
  </choose>
</select>
  • where-if
java 复制代码
//只有传入参数不为空时,才进行where语句判断
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

最终版

java 复制代码
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
      <choose>
        <when test="title != null">
          title like #{title}
        </when>
        <when test="author != null and author.name != null">
          AND author_name like #{author.name}
        </when>
      </choose>
  </where>
</select>

联表查询

java 复制代码
<!-- 定义结果映射 -->
<resultMap id="studentWithCoursesResultMap" type="Student">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <!-- 使用collection处理课程列表 -->
    <collection property="courses" ofType="Course">
        <id property="id" column="course_id"/>
        <result property="courseName" column="course_name"/>
    </collection>
</resultMap>

<!-- 查询语句 -->
<select id="findStudentByNameWithCourses" resultMap="studentWithCoursesResultMap">
    SELECT 
        s.id,
        s.name,
        c.id AS course_id,
        c.course_name
    FROM 
        student s
    LEFT JOIN student_course sc ON s.id = sc.student_id
    LEFT JOIN course c ON sc.course_id = c.id
    WHERE s.name = #{name};
</select>

添加

添加结果可通过异常捕获判断,需要手动提交事务sqlSession.commit()

  • openSessio():默认开启事务,需要手动提交
  • openSessio(true):自动提交事务
java 复制代码
<insert id = "addUser">
   insert into user(name, status)
    values(#{name}, #{status});
</insert>

主键返回

java 复制代码
<insert id = "addUser" useGeneratedKey="true" keyProPerty="id">

修改

可以返回void ,也可以返回int

java 复制代码
<update id="updateUser">
	update user
	set
		name = #{name},
		status = #{status}
	where id = #{id};
</update>

动态修改

set标签

java 复制代码
<update id="updateUser">
	update user
	<set>
		<if test="name != null and name != ''">
			name = #{name},
		</if>
		<if test="status != null and status != ''">
			status = #{status}
		</if>
      </set>
	where id = #{id};
</update>

删除

java 复制代码
<delete id = "deleteUserById">
	delete from user where id = #{id}
</delete>

批量删除

前端封装数组int[] ids

java 复制代码
//可以用@Param('ids')起别名代替array,separator分隔符
<delete id = "deleteUserById">
	delete from user 
	where id in
	<foreach collection="array" item="id" separator=",">
		id = #{id}
	</foreach>
        ;
</delete>
相关推荐
前端付豪44 分钟前
美团 Flink 实时路况计算平台全链路架构揭秘
前端·后端·架构
MikeWe1 小时前
理解深度学习框架计算图的动态图与静态图:机制、实现与应用
后端
Android洋芋1 小时前
从零到一构建企业级TTS工具:实战指南与优化策略
后端
chanalbert1 小时前
AI大模型提示词工程研究报告:长度与效果的辩证分析
前端·后端·ai编程
Android洋芋1 小时前
深度解析Android音频焦点处理与实战开发:从无声问题到企业级解决方案
后端
海风极客1 小时前
Go语言开发小技巧&易错点100例(十七)
后端·面试·github
海风极客1 小时前
Go语言开发小技巧&易错点100例(十六)
后端·面试·github
梅一一1 小时前
JavaScript 通吃指南:从浏览器到你的LED灯
前端·javascript·后端
我崽不熬夜1 小时前
你真的掌握了Java多线程编程吗?并发的这些秘密你可能还不知道!
java·后端·java ee
麻衣带我去上学1 小时前
Spring依赖注入源码学习:基于注解的DI源码解析
java·后端·spring