配置解析

核心配置文件

依序

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境 变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

properties优化

可以通过properties属性来实现引用配置文件

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/库名?
useSSL=true&useUnicode=true&characterEncoding=utf8
username=用户名
password=密码

引入

<properties resource="db.properties">
    <property name="配置文件中没有的参数的名字" value="值"/>
</properties>
  • 可以增加文件中没有的值
  • 当都有的时候,以外部文件位置为准

typeAliases

给长的名字设置一个短的名字,方便易用

实体类

<typeAliases>
        <typeAlias type="top.wmgx.pojo.User" alias="User"/>
</typeAliases>

在用的时候可以不写那一大长串,直接写User就可以了

直接指定包名

当一个包下的所有实体类都要起别名,可以直接指定一个包,默认的别名是类名,首字母小写

<typeAliases>
    <package name="top.wmgx.pojo"/>
</typeAliases>

如果此种方法下想要自定义别名,可以通过注解的方式

@Alias("别名")
public class YourClass{
    
}

日志

STDOUT_LOGGING(标准日志)

直接在配置文件中配置

<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

Log4j

  1. 导入log4j的包

        <dependencies>
            <!-- https://mvnrepository.com/artifact/log4j/log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
        </dependencies>
    
  2. 配置log4j的配置文件

    log4j.properties

    log4j.rootLogger=debug, stdout, R
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    # Pattern to output the caller's file name and line number.
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=example.log
    log4j.appender.R.MaxFileSize=100KB
    # Keep one backup file
    log4j.appender.R.MaxBackupIndex=5
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
    
  3. 配置

    <settings>
            <setting name="logImpl" value="LOG4J"/>
    </settings>
    

属性名和字段名不一致

  1. select 语句中起别名

  2. resultMap

    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--column数据库中的字段,property实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserById" resultMap="UserMap" parameterType="int">
        /*定义sql*/
        select * from mybatis.user where id = #{id};
    </select>
    

    一致的可以省略不写

分页

使用Limit分页

select * from user limit startIndex,pageSize; #startIndex 从0开始

可以传入一个Map几何,其中包含startindex和pageSize即可

  1. 接口

    List<User> getUserByLimit(Map<String,Integer> map);
    
  2. Mapper.xml

    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>
    

    Map中的key-value可以像属性一样直接用

  3. 测试

    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);
    
        List<User> userList = mapper.getUserByLimit(map);
        System.out.println(userList);
        sqlSession.close();
    }
    

RowBounds分页

  1. 接口

    List<User> getUserByRowBounds();
    
  2. Mapper.xml

    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>
    
  3. 测试

    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
        //通过java代码层面实现分页
        List<User> userList = sqlSession.selectList("top.wmgx.Dao.UserMapper.getUserByRowBounds",null,rowBounds);
    
        System.out.println(userList);
        sqlSession.close();
    }
    

注解开发

  1. 接口

    @Select(value = "select * from user")
    List<User> getUsers();
    //若存在多个参数,则需要@Param("参数名")注解
    @Select("select * from user where id = #{id} or name = #{name}")
    User getUserByID(@Param("id")int id,@Param("name")String name);
    
  2. 绑定接口

    <mappers>
    <mapper class="top.wmgx.Dao.UserMapper"/>
    </mappers>
    
  • 本质:反射机制实现

  • 底层:动态代理!

@Param

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名

Lombok

使用步骤

  1. 安装插件

  2. 导入jar包

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
    
   @Data:无参构造,get、set、toSring、hashcode、equals
   @AllArgsConstructor
   @NoArgsConstructor
   @ToString
   @EqualsAndHashCode

一对多,多对一(属性中为集合或者引用数据类型)

按查询嵌套处理(多对一)

<!--
思路:
    1、查询所有的学生信息
    2、根据查询出来的学生的id的tid,寻找对应的老师! -子查询
-->

<select id="getStudent" resultMap="StudentTeacher">
	select * from student
</select>

<resultMap id="StudentTeacher" type="top.wmgx.pojo.Student">
    <!--复杂的属性,我们需要单独处理  对象:association  集合:collection-->
    <association property="teacher" column="tid" javaType="top.wmgx.pojo.Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="top.wmgx.pojo.Teacher">
    select * from teacher where id = #{id}
</select>

按照结果嵌套处理(多对一)

<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from student s,teacher t
    where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="top.wmgx.pojo.Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="top.wmgx.pojo.Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
    </association>

</resultMap>

按查询嵌套处理(多对一)

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="top.wmgx.pojo.Teacher">
    <collection property="students" javaType="ArrayList" ofType="top.wmgx.pojo.Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="top.wmgx.pojo.Student">
    select * from mybatis.student where tid = #{tid}
</select>

按照结果嵌套处理(一对多)

<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from student s,teacher t
    where s.tid=t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="top.wmgx.pojo.Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--复杂的属性,我们需要单独处理  对象:association  集合:collection
        javaType="" 指定属性的类型
        集合中的泛型信息,我们使用ofType获取
    -->
    <collection property="students" ofType="top.wmgx.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

javaType:JavaType用来指定实体类中属性的类型

ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

动态SQL

动态SQL就是指根据不同的条件生成不同的SQL语句**

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

IF

<select id="queryBlogIF" parameterType="map" resultType="top.wmgx.pojo.Blog">
    select * from bolg where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>

trim ,where

select * from mybatis.bolg
<where>
<if test="title != null">
    title = #{title}
</if>
<if test="author != null">
    and author = #{author}
</if>
</where>

trim, set

<update id="updateBlog" parameterType="map">
    update bolg
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
    </set>
    where id = #{id}
</update>

choose (when, otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="top.wmgx.pojo.Blog">
    select * from bolg
    <where>
        <choose>
            <when test="title != null">
                title=#{title}
            </when>
            <when test="author!=null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </where>
</select>

SQL片段

  1. 使用SQL标签抽取公共的部分

    <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的地方使用Include标签引用即可

    <select id="queryBlogIF" parameterType="map" resultType="top.wmgx.pojo.Blog">
        select * from mybatis.bolg
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>
    

Foreach

select * from user where id in
	<foreach item="id" index="index" collection="ids"
             open="(" sparator="," close=")" >
        #{id}
</foreach>

学习视频https://www.bilibili.com/video/av69742084