1:基本配置
<!-- configuration配置父标签内,所有的子标签都是有顺序的,位置不可以随意调换,必须是:properties, settings ...,可以没有,但是如果有必须在对应顺序位置出现 --> <configuration> <!-- 1、properties属性:自定义核心属性配置,也可以引入外部的属性配置文件,比如jdbc.properties连接配置文件 resource属性:指定外部属性配置文件,优先级高于内部property子标签属性配置,可以单独使用,如果二者同时存在,优先以外部为主 --> <!--<properties resource="jdbc.properties">--> <!-- <property name="driverClass" value="com.mysql.jdbc.Driver"/>--> <!-- <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/animedb?useUnicode=true&characterEncoding=utf-8&useSSL=false"/>--> <!-- <property name="user" value="root"/>--> <!-- <property name="password" value="1234"/>--> <!--</properties>--> 实际: <properties resource="jdbc.properties"/> <!-- 2、是否开启驼峰命名自动映射,默认是关闭的-false,可以手动打开-true,作用:从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 3、typeAliases配置:类型别名处理,作用:为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写 --> <typeAliases> <!-- 单个取别名,在SQL的xml映射文件中的resultType就不需要写全类名,而直接使用别名,不区分大小写 --> <!--<typeAlias type="com.kgc.mybatis.bean.Anime" alias="anime"/>--> <!-- 批量取别名,指定的是实体所在的父包路径,自动将指定包及子包中所有的实体批量取别名,默认是类名的首字母小写,不区分大小写 --> <!-- 建议:如果没有安装插件,从SQL映射xml文件中,无法直接通过别名定位到目标实体类,不利于代码解读,能写全类名尽量直接写全类名 --> <package name="com.kgc.mybatis.bean"/> </typeAliases> <!--4、environments配置:环境配置,可以配置多个环境,比如:开发、测试和生产环境需要有不同的配置,可以灵活切换 注意:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境,即必须保证default指定的默认环境id是其中一个环境的id值 --> <environments default="development_test"> <!-- 开发环境 --> <environment id="development_dev"> <!-- 事务管理,MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"),不需要记,以后框架整合,会统一交给spring管理 官方建议:如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖此处的配置 --> <transactionManager type="JDBC"/> <!-- 数据源配置:标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源,三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"),也不需要记,以后框架整合,会统一交给spring管理 --> <dataSource type="POOLED"> <property name="driver" value="${driverClass}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${user}"/> <property name="password" value="${password}"/> </dataSource> </environment> <!-- 测试环境 --> <environment id="development_test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driverClass}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${user}"/> <property name="password" value="${password}"/> </dataSource> </environment> <!-- 生产环境 --> <environment id="development_pro"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driverClass}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${user}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 5、mappers配置:映射器,指定SQL映射文件的加载,作用:告诉 MyBatis 到哪里去找映射文件 --> <mappers> <!-- 单个SQL映射文件的加载,如果是多级目录,使用分隔符不是 . 而是 / --> <!--<mapper resource="AnimeMapper.xml"/>--> <!--<mapper resource="com/kgc/mybatis/mapper/AnimeMapper.xml"/>--> <!-- 批量SQL映射文件加载,只需要指定mapper接口的所在包,将包内的映射器接口实现全部注册为映射器,即根据接口全类名找对应的SQL映射文件 --> <!-- 前提条件:必须要保证接口和SQL映射文件是同名同路径的,即:接口名和SQL映射文件名相同,且接口报名和SQL映射文件路径名相同 --> <!-- 也可以自定义路径:必须是spring整合mybatis,提供了自定义的方式,目前做不到 --> <package name="com.kgc.mybatis.mapper"/> </mappers> </configuration>
2:sql映射文件
<!-- SQL语句映射文件: namespace:名称空间 1、单独使用SqlSession的方法,可以随意的定义,仅限于全限定名的方式,指定SQL语句唯一标识字符串使用 2、面向接口开发时,不可以随便写,必须是某个接口的全类名(全路径名:包名+类名) --> <!--<mapper namespace="wusuowei">--> <mapper namespace="com.kgc.mybatis.mapper.AnimeMapper"> <!-- select标签:查询标签 id属性:select标签的唯一标识,在面向接口开发是,对应的是namespace指定接口的某个方法名 resultType属性:查询结果的映射目标类型,自动将查询数据映射到指定的类型对象中,返回 #{id}:获取调用接口,传递的参数值 --> <select id="selectAnime" resultType="com.kgc.mybatis.bean.Anime"> select * from animes where id = #{id} </select> </mapper>
3:使用调用
//(1) 指定mybatis的核心配置文件路径 String resource = "mybatis-config.xml"; //(2) 使用mybatis提供的Resources工具类,读取核心配置文件,转换为输入流对象 InputStream inputStream = Resources.getResourceAsStream(resource); //(3) 使用SqlSessionFactoryBuilder对象的build方法,基于上一步获取的输入流对象,构建SqlSessionFactory的实例对象(DefaultSqlSessionFactory) SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); System.out.println(sqlSessionFactory); // 通过SqlSessionFactory的实例对象获取SqlSession的实例,SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 try (SqlSession session = sqlSessionFactory.openSession()) { // 通过获取的SqlSession的实例,执行查询数据操作 // statement – Unique identifier matching the statement to use. 准备要执行的SQL语句的唯一标识字符串(mybatis框架可以识别的,目的是通过此标识找到要执行的SQL语句) // parameter – A parameter object to pass to the statement. 准备要执行的SQL语句的参数值 // 根据动漫的编号,查询动漫的详情,弊端:必须要了解SqlSession的所有方法 // Anime anime = (Anime) session.selectOne("wusuowei.selectAnime", 101); // System.out.println(anime); // 面向接口开发,推荐使用方式 AnimeMapper animeMapper = session.getMapper(AnimeMapper.class); System.out.println(animeMapper); // 直接就可以通过调用接口的方法,执行对应的SQL语句,并返回结果,不需要关系mybatis底层是调用哪个方法的 Anime anime = animeMapper.selectAnime(102); System.out.println(anime);
3:查询
<mapper namespace="com.kgc.mybatis.mapper.AnimeMapper"> <!-- insert,update,delete操作小结: insert-插入标签,update-修改标签,delete-删除标签 id属性:对应就是namespace指定接口中的方法名 parameterType属性:指定接口方法入参类型,可写可不写(mybatis可以根据接口方法,自动推断类型),建议不写(写多了容易出错) 注意:增删改操作,和select查询最大的区别是,返回只有影响行数,所以没有resultType属性,而查询必须有结果返回类型 insert: useGeneratedKeys属性:insert标签的属性,告诉mybatis,执行插入操作,需要返回自增的主键值 keyProperty属性:insert标签的属性,指定返回的自增主键值,交给入参实体的哪个属性保存,一般都是主键属性保存,接口执行后,入参实体中可以获取自增主键值 --> <!--int insertAnime(Anime animeForm);--> <insert id="insertAnime" useGeneratedKeys="true" keyProperty="id"> insert into `animes`( `cid`, `name`, `author`, `actor`, `produce`, `create_date` ) values ( #{cid}, #{name}, #{author}, #{actor}, #{produce}, #{createDate} ) </insert> <!-- int updateAnimeById(Anime animeForm); --> <update id="updateAnimeById"> update `animes` set `cid` = #{cid}, `name` = #{name}, `author` = #{author}, `actor` = #{actor}, `produce` = #{produce}, `create_date` = #{createDate} where `id` = #{id} </update> <!--int deleteAnimeById(Integer id);--> <delete id="deleteAnimeById"> delete from `animes` where id = #{id} </delete> <!-- select查询小结: id属性:对应就是namespace指定接口中的查询方法名 resultType属性:指定接口返回的目标实体类型(建议使用全类名,也可以使用别名) parameterType属性:指定接口方法入参类型,可写可不写,建议不写 #{id}:获取参数,告诉 MyBatis 创建一个预处理语句(PreparedStatement)参数,且参数在 SQL 中会由一个“?”来标识,并被传递到一个新的预处理语句中 如果接口只有一个参数,获取参数名,可以随便写,建议:跟形参名保持一致 --> <!-- Anime selectAnimeById(Integer id); --> <select id="selectAnimeById" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `id` = #{abc} </select> <!-- Anime selectAnimeByNameAndCid(String name, Integer cid); --> <select id="selectAnimeByNameAndCid" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `name` = #{name} and `cid` = #{cid} </select> <!--Anime selectAnimeByAuthorAndCid(Anime queryAnime);--> <select id="selectAnimeByAuthorAndCid" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `author` = #{queryAnime.author} and `cid` = #{queryAnime.cid} </select> <!--Anime selectAnimeByActorAndCid(Map<String, Object> queryMap);--> <select id="selectAnimeByActorAndCid" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `actor` = #{actor} and `cid` = #{cid} </select> <!--Anime selectAnimeByProduceAndCid(@Param("produce") String produce, @Param("cid") Integer cid, @Param("tableName") String tableName);--> <select id="selectAnimeByProduceAndCid" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from ${tableName} where `produce` = #{produce} and `cid` = #{cid} </select> <!--List<Anime> selectAnimeListByCid(Integer cid);--> <select id="selectAnimeListByCid" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `cid` = #{cid} </select> <!--List<Anime> selectAnimeListByName(String queryName);--> <select id="selectAnimeListByName" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` <!--where `name` like '%#{queryName}%' 错误的--> <!--where `name` like concat('%', #{queryName}, '%')--> where `name` like '%${queryName}%' </select> </mapper>
4:入参处理
mybatis入参处理: * 1、单个参数:可以随便的指定别名获取参数值,建议跟形参名一致 * 2、多个参数:默认情况下,如果不定义别名,可以使用mybatis底层的内置参数:0,1,... 或者param1,param2,... * 3、多个参数:也可以使用自定义别名,通过mybatis的注解@Param("别名"),指定参数别名,SQL映射文件中,获取参数,就只能是自定义别名或者param1,param2,... * 4、实体参数:可以将参数封装到实体对象中,SQL映射文件中,直接根据实体的属性名获取属性值,如果给实体参数起别名,获取参数值就必须通过 别名.实体属性名,获取参数值 * 5、集合参数:都是使用map入参,获取参数,直接使用map集合的key值,获取对应的参数值,比如:#{map中存放的那个key} * * mybatis获取参数处理: * 1、方式1:#{},可以获取普通参数,自定义参数,实体参数,集合参数等,底层使用的是?占位符,会进行预编译处理,可以防止SQL注入问题,安全性高,但是不可以进行表达式运算 * 2、方式2:${},正常情况下,跟#{}获取参数的写法没有区别(区别:不能随意获取参数,不能使用内置参数,必须起别名),底层是字符串拼接,不是占位符,不安全,当#{}解决不了,就必须使用${},比如:动态表名,动态列名,表达式运算等 * 建议:mybatis的SQL映射文件中,能优先使用#{},就必须使用,除非特殊情况,必须使用字符串拼接,才可以使用${} */
5:mybaties工具类
package com.kgc.mybatis.util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * Created by zhukang mybatis通用工具类 */ public class MybatisUtil { // Mybatis核心配置文件 private static final String MYBATIS_CONFIG_RESOURCE = "mybatis-config.xml"; // Mybatis的SqlSession工厂 private static SqlSessionFactory sqlSessionFactory; static { InputStream inputStream = null; try { // 读取mybatis-config配置文件 inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG_RESOURCE); // 创建SqlSessionFactory对象 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } finally { try { if(null != inputStream) inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * @author zhukang * @return * @description 获取SqlSession对象 */ public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } /** * @author zhukang * @return void * @description 关闭SqlSession */ public static void closeSqlSession(SqlSession sqlSession) { // 提交并关闭 sqlSession.commit(); sqlSession.close(); } }
6:mybaties中动态标签使用
<?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="com.kgc.mybatis.mapper.AnimeMapper"> <!--List<Anime> selectAnimesByConditionUseIf(Integer cid, String author);--> <select id="selectAnimesByConditionUseIf" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` where `create_date` < now() <!-- <if>动态标签:判断参数是否满足test指定的条件,如果满足,就执行if(增加if标签中的SQL条件语句) 注意:test里面使用的参数,可以是mybatis的默认参数,也可以是实体属性名,但是不能是没有指定别名的参数名(尤其是单个参数,也必须起别名,否则异常) --> <if test="cid != null and cid != 0"> and cid = #{cid} </if> <if test="author != null"> and author like concat('%', #{author}, '%') </if> </select> <!--List<Anime> selectAnimesByConditionUseIfWhere(@Param("cid") Integer cid, @Param("author") String author);--> <select id="selectAnimesByConditionUseIfWhere" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` <!-- <where>+<if>动态标签组合:当where标签中,有if条件成立时,自动增加where关键字,如果所有的if都不成立,也不会多增加where关键字 当where标签中,if条件成立,增加的SQL条件语句,前面多出现一个and或者or关键字,会被自动过滤(剔除),但是末尾出现的,不会被剔除 where标签中,也可以增加固定条件,在实际开发过程中,建议where标签中,必须写固定条件,不能全部写if条件判断,因为一旦所有if条件都不满足,会导致不带条件查全表,影响查询效率(降低性能) --> <where> <if test="cid != null and cid != 0"> and cid = #{cid} </if> <if test="author != null"> and author like concat('%', #{author}, '%') </if> <!-- 增加固定条件,即便前面所有的if都不满足,此条件仍然存在 ,一般增加的固定条件都是日期居多,不如7条,或者一个月等--> and `create_date` < now() </where> </select> <!--List<Anime> selectAnimesByConditionUseIfTrim(@Param("cid") Integer cid, @Param("author") String author);--> <select id="selectAnimesByConditionUseIfTrim" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` <!-- <trim>+<if>动态标签:可以实现动态SQL的定制操作,比如:where标签无法屏蔽末尾多出来的and或者or关键字,前缀和后缀增加内容,只有标签中有if条件成立(需要增加条件SQL语句),才会生效 prefix属性:增加前缀固定字符串 prefixOverrides属性:前缀覆盖(自动剔除指定的关键字) suffix属性:增加后缀固定字符串 suffixOverrides属性:后缀覆盖(自动剔除指定的关键字) --> <trim prefix=" where " prefixOverrides="and |or" suffix=";" suffixOverrides="and |or"> <if test="cid != null and cid != 0"> cid = #{cid} and </if> <if test="author != null"> author like concat('%', #{author}, '%') and </if> </trim> </select> <!--int updateAnimeByConditionUseIfSet(Anime animeForm);--> <update id="updateAnimeByConditionUseIfSet"> update `animes` <set> <if test="cid != null">`cid` = #{cid},</if> <if test="name != null">`name` = #{name},</if> <if test="author != null">`author` = #{author},</if> <if test="actor != null">`actor` = #{actor},</if> <if test="produce != null">`produce` = #{produce},</if> <if test="createDate != null">`create_date` = #{createDate},</if> </set> where `id` = #{id} </update> <!--int updateAnimeByConditionUseIfTrim(Anime animeForm);--> <update id="updateAnimeByConditionUseIfTrim"> <trim prefix=" update `animes` set " prefixOverrides="," suffixOverrides=","> <if test="cid != null">`cid` = #{cid},</if> <if test="name != null">`name` = #{name},</if> <if test="author != null">`author` = #{author},</if> <if test="actor != null">`actor` = #{actor},</if> <if test="produce != null">`produce` = #{produce},</if> <if test="createDate != null">`create_date` = #{createDate},</if> </trim> where `id` = #{id} </update> <!--List<Anime> selectAnimesByConditionUseChooseWhenOtherwise(@Param("cid") String cid);--> <select id="selectAnimesByConditionUseChooseWhenOtherwise" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` <where> <!--mybatis没有if...else if...else if...else,只能通过choose+when+otherwise实现,也类似于switch选择结构--> <choose> <!--字符串内容比较,可以使用双引号,但是test条件要改为单引号--> <!--<when test='cid != null and cid == "1"'>--> <!--<when test='cid != null and cid == "A"'>--> <when test='cid != null and cid == "分类1"'> and cid = 1 </when> <!--推荐:字符串内容比较,如果是数字字符串,字符字符串,要使用单引号.toString(),如果就是单词的字符串,可以直接比较 --> <!--<when test="cid != null and cid eq '2'.toString()">--> <!--<when test="cid != null and cid eq 'B'.toString()">--> <when test="cid != null and cid eq '分类2'"> and cid = 2 </when> <otherwise> and cid = 3 </otherwise> </choose> </where> </select> <!--List<Anime> selectAnimesByConditionUseForeach(@Param("ids") List<Integer> ids);--> <select id="selectAnimesByConditionUseForeach" resultType="com.kgc.mybatis.bean.Anime"> select `id`, `cid`, `name`, `author`, `actor`, `produce`, `create_date` from `animes` <!--语法:where id in (id1, id2, id3, ...)--> <!-- <foreach>标签:可以迭代对象有:list,set,数组等 collection属性:指定要迭代的集合 item属性:起别名,方便使用此别名获取集合中参数值 open属性:循环开始,前面增加固定内容字符串 close属性:循环结束,后面增加固定内容字符串 separator属性:指定分隔符,每循环一次,就增加一个分隔符,如果循环结束,末尾会自动省略 --> <!--写法1:起自定义别名,遍历--> <!--<where> <foreach collection="ids" item="id" open=" id in ( " close=" )" separator=", "> #{id} </foreach> </where>--> <!--写法2:内置参数别名-list,但是不能跟自定义别名混用,遍历--> <!--<where> <foreach collection="list" item="id" open=" id in ( " close=" )" separator=", "> #{id} </foreach> </where>--> <!--写法3:自定义别名,不用where标签 --> <!--<foreach collection="ids" item="id" open=" where id in ( " close=" )" separator=", "> #{id} </foreach>--> <!--写法4:自定义别名,不用where标签,用trim --> <!--<trim prefix=" where id in "> <foreach collection="ids" item="id" open="( " close=" )" separator=", "> #{id} </foreach> </trim>--> <!--写法5:自定义别名,不用in,用or --> <foreach collection="ids" item="id" open=" where " close=" ;" separator=" or "> id = #{id} </foreach> </select> <!--int insertAnimeByConditionIfTrim(Anime animeForm);--> <insert id="insertAnimeByConditionIfTrim"> <trim prefix="insert into `animes` (" suffix=")" suffixOverrides=","> <if test="cid != null">`cid`,</if> <if test="name != null">`name`,</if> <if test="author != null">`author`,</if> <if test="actor != null">`actor`,</if> <if test="produce != null">`produce`,</if> <if test="createDate != null">`create_date`,</if> </trim> <trim prefix=" values (" suffix=")" suffixOverrides=","> <if test="cid != null">#{cid},</if> <if test="name != null">#{name},</if> <if test="author != null">#{author},</if> <if test="actor != null">#{actor},</if> <if test="produce != null">#{produce},</if> <if test="createDate != null">#{createDate},</if> </trim> </insert> <!-- mybatis批量处理:一般都是针对批量插入和批量删除,很少有批量更新 插入:insert into animes(x, x, x, ...) values (?, ?, ?, ...), (?, ?, ?, ...), (?, ?, ?, ...), ......; 删除:delete from animes where id in (?, ?, ?, ...); --> <!--int insertCategoryBatchUseForeach(List<Category> categoryList);--> <insert id="insertCategoryBatchUseForeach"> insert into `category` (`name`) values <foreach collection="list" item="category" separator=","> (#{category.name}) </foreach> </insert> </mapper>