MyBatis
快速入门
-
创建xml文件:mybatis-config.xml
-
配置
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>
-
创建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>
-
创建SqlSessionFactory以及SqlSession
javaString 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代理开发
-
定义Mapper接口:xml文件要和接口在同一目录下,例如resources创建top/zendee/mapper
-
命名空间改为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>
-
映射文件的id 和方法名 相同,返回值相同
-
使用接口
javaBlogMapper 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>
特殊字符处理
- 转义字符:<,例如< <(小于)
- <! [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>