概念: SQL配置文件用於配置SQL語句塊以及SQL相關配置:java
mybatis內置別名.mdsql
源碼: /mybatis3/數據庫
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><properties resource="jdbc/db.propertiesyap"/><!--別名掃描--><typeAliases><!--<typeAlias type="com.yap.pojo.Student" alias="student"/>--><package name="com.yap.pojo"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><mappers><mapper resource="mapper/student-mapper.xml"/><mapper resource="mapper/teacher-mapper.xml"/><mapper resource="mapper/worker-mapper.xml"/></mappers></configuration>複製代碼
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="studentSpace"><cache readOnly="true"/><!--sql重用快--><sql id="cols">`id`, `name`, `gender`, `age`, `info`</sql><insert id="insert" parameterType="student" useGeneratedKeys="true" keyProperty="id">INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><insert id="insertWithSelectKey"><selectKey order="AFTER" keyProperty="id" resultType="int">SELECT last_insert_id()</selectKey>INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><select id="findById" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `id` = #{id}</select><select id="findLikeName" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like '%${value}%'</select><select id="findLikeNameWithConcat" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like concat('%', #{name}, '%')</select><update id="updateById">UPDATE `student` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}</update><delete id="deleteById">DELETE FROM `student` WHERE `id` = #{id}</delete><resultMap id="findAllMap" type="student"><id column="name" property="id" javaType="int" jdbcType="INT"/><result column="name" property="name" javaType="string" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="VARCHAR"/><result column="gender" property="gender"/><result column="info" property="info"/></resultMap><select id="findAll" resultMap="findAllMap">SELECT<include refid="cols"/>FROM `student`</select></mapper>複製代碼
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.yap.mapper.WorkerMapper"><insert id="insert" useGeneratedKeys="true" keyProperty="id">INSERT INTO `worker` (`id`, `name`, `gender`, `age`, `info`) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><select id="findById" resultType="worker">SELECT `id`, `name`, `gender`, `age`, `info` FROM `worker` WHERE `id` = #{id}</select><select id="findLikeName" resultType="worker">SELECT `id`, `name`, `gender`, `age`, `info` FROM `worker` WHERE `name` like concat('%', #{name}, '%')</select><update id="updateById">UPDATE `worker` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}</update><delete id="deleteById">DELETE FROM `worker` WHERE `id` = #{id}</delete></mapper>複製代碼
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.yap.mapper.TeacherMapper"><cache-ref namespace="studentSpace"/></mapper>複製代碼
package com.yap.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;/** * @author yap */@Data@AllArgsConstructor@NoArgsConstructorpublic class Teacher implements Serializable {private Integer id;private String name;private Integer gender;private Integer age;private String info; }複製代碼2. DML語句塊
流程: DML操做能夠省略 parameterType,必須省略 resultType:apache
源碼: /mybatis3/緩存
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="studentSpace"><cache readOnly="true"/><sql id="cols">`id`, `name`, `gender`, `age`, `info`</sql><insert id="insert" parameterType="student" useGeneratedKeys="true" keyProperty="id">INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><insert id="insertWithSelectKey"><selectKey order="AFTER" keyProperty="id" resultType="int">SELECT last_insert_id()</selectKey>INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><select id="findById" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `id` = #{id}</select><select id="findLikeName" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like '%${value}%'</select><select id="findLikeNameWithConcat" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like concat('%', #{name}, '%')</select><update id="updateById">UPDATE `student` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}</update><delete id="deleteById">DELETE FROM `student` WHERE `id` = #{id}</delete><resultMap id="findAllMap" type="student"><id column="name" property="id" javaType="int" jdbcType="INT"/><result column="name" property="name" javaType="string" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="VARCHAR"/><result column="gender" property="gender"/><result column="info" property="info"/></resultMap><select id="findAll" resultMap="findAllMap">SELECT<include refid="cols"/>FROM `student`</select></mapper>複製代碼
package com.yap.crud;import com.yap.pojo.Student;import com.yap.util.MyBatisUtil;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;/** * @author yap */public class StudentTest {private SqlSessionFactory factory = MyBatisUtil.getFactory("mybatis-crud.xml");@Testpublic void insert() { Student zhaosi = new Student(null, "趙四", 1, 58, "亞洲舞王"); Student liunneng = new Student(10, "劉能", 0, 19, "玉田花圃"); SqlSession session = factory.openSession();try { session.insert("studentSpace.insert", zhaosi); session.insert("studentSpace.insert", liunneng); session.commit(); System.out.println(zhaosi); System.out.println(liunneng); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } } }複製代碼
@Testpublic void insertWithSelectKey() { Student dajiao = new Student(null, "大腳", 0, 18, "大腳超市"); SqlSession session = factory.openSession();try { session.insert("studentSpace.insertWithSelectKey", dajiao); session.commit(); System.out.println(dajiao); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }複製代碼
@Testpublic void updateById() { SqlSession session = factory.openSession(); Student zhaosi = new Student(1, "謝廣坤", 1, 60, "廣坤山貨");try { session.update("studentSpace.updateById", zhaosi); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }複製代碼
@Testpublic void deleteById() { SqlSession session = factory.openSession();try { session.delete("studentSpace.deleteById", 1); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }複製代碼3. DQL語句塊
流程: DQL能夠省略 parameterType,必須使用 resultType 指定返回值或其泛型的類全名或別名:安全
jdbcType枚舉類型.pngsession
源碼: /mybatis3/mybatis
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="studentSpace"><cache readOnly="true"/><sql id="cols">`id`, `name`, `gender`, `age`, `info`</sql><insert id="insert" parameterType="student" useGeneratedKeys="true" keyProperty="id">INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><insert id="insertWithSelectKey"><selectKey order="AFTER" keyProperty="id" resultType="int">SELECT last_insert_id()</selectKey>INSERT INTO `student` (<include refid="cols"/>) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><select id="findById" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `id` = #{id}</select><select id="findLikeName" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like '%${value}%'</select><select id="findLikeNameWithConcat" resultType="student">SELECT<include refid="cols"/>FROM `student` WHERE `name` like concat('%', #{name}, '%')</select><update id="updateById">UPDATE `student` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}</update><delete id="deleteById">DELETE FROM `student` WHERE `id` = #{id}</delete><resultMap id="findAllMap" type="student"><id column="name" property="id" javaType="int" jdbcType="INT"/><result column="name" property="name" javaType="string" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="VARCHAR"/><result column="gender" property="gender"/><result column="info" property="info"/></resultMap><select id="findAll" resultMap="findAllMap">SELECT<include refid="cols"/>FROM `student`</select></mapper>複製代碼
@Testpublic void findById() {try (SqlSession session = factory.openSession();) { System.out.println((Student) session.selectOne("studentSpace.findById", 1)); System.out.println((Student) session.selectOne("studentSpace.findById", new Student(1, null, null, null, null))); } catch (Exception e) { e.printStackTrace(); } }複製代碼
@Testpublic void findLikeName() {try (SqlSession session = factory.openSession()) { System.out.println(session.selectList("studentSpace.findLikeName", "劉")); System.out.println(session.selectList("studentSpace.findLikeName", "'or'")); } catch (Exception e) { e.printStackTrace(); } }複製代碼
@Testpublic void findLikeNameWithConcat() {try (SqlSession session = factory.openSession()) { System.out.println(session.selectList("studentSpace.findLikeNameWithConcat", "劉")); System.out.println(session.selectList("studentSpace.findLikeNameWithConcat", "'or'")); } catch (Exception e) { e.printStackTrace(); } }複製代碼
複製代碼4. 接口開發
流程: 接口動態代理模式須要額外開發一個遵照對應關係的java接口:app
源碼: /mybatis3/ide
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.yap.mapper.WorkerMapper"><insert id="insert" useGeneratedKeys="true" keyProperty="id">INSERT INTO `worker` (`id`, `name`, `gender`, `age`, `info`) VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})</insert><select id="findById" resultType="worker">SELECT `id`, `name`, `gender`, `age`, `info` FROM `worker` WHERE `id` = #{id}</select><select id="findLikeName" resultType="worker">SELECT `id`, `name`, `gender`, `age`, `info` FROM `worker` WHERE `name` like concat('%', #{name}, '%')</select><update id="updateById">UPDATE `worker` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}</update><delete id="deleteById">DELETE FROM `worker` WHERE `id` = #{id}</delete></mapper>複製代碼
package com.yap.mapper;import com.yap.pojo.Worker;import java.util.List;/** * @author yap */public interface WorkerMapper {/** * 根據主鍵查詢一條信息 * * @param id 主鍵 * @return 對應主鍵的一條信息 */Worker findById(int id);/** * 添加一條工人信息 * * @param worker 工人實體 */void insert(Worker worker);/** * 按照姓名模糊查詢全部符合條件的工人 * * @param name 姓名的模糊查詢部分 * @return 全部符合條件的工人 */List<Worker> findLikeName(String name);/** * 根據主鍵修改一條工人信息 * * @param worker 工人實體 */void updateById(Worker worker);/** * 根據主鍵刪除工人 * * @param id 主鍵 */void deleteById(int id); }複製代碼
package com.yap.crud;import com.yap.mapper.WorkerMapper;import com.yap.pojo.Worker;import com.yap.util.MyBatisUtil;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;/** * @author yap */public class WorkerTest {private SqlSessionFactory factory = MyBatisUtil.getFactory("mybatis-crud.xml");@Testpublic void insert() { SqlSession session = factory.openSession(); WorkerMapper workerMapper = session.getMapper(WorkerMapper.class);try { workerMapper.insert(new Worker(null, "趙四", 1, 58, "亞洲舞王")); workerMapper.insert(new Worker(null, "趙五", 1, 58, "亞洲舞王")); workerMapper.insert(new Worker(null, "王四", 1, 58, "亞洲舞王")); workerMapper.insert(new Worker(null, "王五", 1, 58, "亞洲舞王")); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }@Testpublic void findById() {try (SqlSession session = factory.openSession()) { WorkerMapper workerMapper = session.getMapper(WorkerMapper.class); System.out.println(workerMapper.findById(1)); } catch (Exception e) { e.printStackTrace(); } }@Testpublic void findLikeName() {try (SqlSession session = factory.openSession()) { WorkerMapper workerMapper = session.getMapper(WorkerMapper.class); System.out.println(workerMapper.findLikeName("四")); } catch (Exception e) { e.printStackTrace(); } }@Testpublic void updateById() { SqlSession session = factory.openSession(); WorkerMapper workerMapper = session.getMapper(WorkerMapper.class);try { workerMapper.updateById(new Worker(1, "劉能", 1, 58, "村副主任")); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }@Testpublic void deleteById() { SqlSession session = factory.openSession(); WorkerMapper workerMapper = session.getMapper(WorkerMapper.class);try { workerMapper.deleteById(1); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } } }複製代碼
流程: 接口開發模式下,可以使用註解替代SQL語句塊,雖簡化了代碼,但不適用於複雜SQL:
源碼: /mybatis3/
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.yap.mapper.TeacherMapper"><cache-ref namespace="studentSpace"/></mapper>複製代碼
package com.yap.mapper;import com.yap.pojo.Teacher;import org.apache.ibatis.annotations.*;import java.util.List;/** * @author yap */public interface TeacherMapper {/** * 添加一條教師信息 * * @param teacher 教師實體 */@Insert("INSERT INTO `teacher` (`name`, `gender`, `age`, `info`) VALUES (#{name}, #{gender}, #{age}, #{info})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(Teacher teacher);/** * 根據主鍵查詢一條信息 * * @param id 主鍵 * @return 對應主鍵的一條信息 */@Select("SELECT `id`, `name`, `gender`, `age`, `info` FROM `teacher` WHERE `id` = #{id}")Teacher findById(int id);/** * 按照姓名模糊查詢全部符合條件的教師 * * @param name 姓名的模糊查詢部分 * @return 全部符合條件的教師 */@Select("SELECT `id`, `name`, `gender`, `age`, `info` FROM `teacher` WHERE `name` like concat('%', #{name}, '%')")List<Teacher> findLikeName(String name);/** * 根據主鍵修改一條教師信息 * * @param teacher 教師實體 */@Update("UPDATE `teacher` SET `name` = #{name}, `age` = #{age}, `gender` = #{gender}, `info` = #{info} WHERE `id` = #{id}")void updateById(Teacher teacher);/** * 根據主鍵刪除教師 * * @param id 主鍵 */@Delete("DELETE FROM `teacher` WHERE `id` = #{id}")void deleteById(int id); }複製代碼
package com.yap.crud;import com.yap.mapper.TeacherMapper;import com.yap.pojo.Teacher;import com.yap.util.MyBatisUtil;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;/** * @author yap */public class TeacherTest {private SqlSessionFactory factory = MyBatisUtil.getFactory("mybatis-crud.xml");@Testpublic void insert() { SqlSession session = factory.openSession(); TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);try { teacherMapper.insert(new Teacher(null, "趙四", 1, 58, "亞洲舞王")); teacherMapper.insert(new Teacher(null, "趙五", 1, 58, "亞洲舞王")); teacherMapper.insert(new Teacher(null, "王四", 1, 58, "亞洲舞王")); teacherMapper.insert(new Teacher(null, "王五", 1, 58, "亞洲舞王")); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }@Testpublic void findById() {try (SqlSession session = factory.openSession()) { TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class); System.out.println(teacherMapper.findById(1)); } catch (Exception e) { e.printStackTrace(); } }@Testpublic void findLikeName() {try (SqlSession session = factory.openSession()) { TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class); System.out.println(teacherMapper.findLikeName("四")); } catch (Exception e) { e.printStackTrace(); } }@Testpublic void updateById() { SqlSession session = factory.openSession(); TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);try { teacherMapper.updateById(new Teacher(1, "劉能", 1, 58, "村副主任")); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } }@Testpublic void deleteById() { SqlSession session = factory.openSession(); TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);try { teacherMapper.deleteById(1); session.commit(); } catch (Exception e) { session.rollback(); e.printStackTrace(); } finally { session.close(); } } }複製代碼