Mybatis笔记

Mybatis

搭建环境

1.导入依赖

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

<!--打包包括xml和properties的文件-->
        <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>

        </resources>
    </build>

2.构建SqlSession工具类

 public class MybatisUtil {

    static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSessionFactory(){
        return sqlSessionFactory.openSession();
    }
}

3.配置mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="12345678"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/tintin/mapper/xml/UserMapper.xml"/>
  </mappers>
</configuration>

4.创建mapper接口

public interface UserMapper {
    List<User> listUser();
}

5.创建UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tintin.mapper.UserMapper">
    <select id="listUser" resultType="com.tintin.entry.User">
        select * from mybatis.user
    </select>
</mapper>
<!-- 增删改查 -->
<!-- 增删改 必须提交事务 sqlSession.commit(); -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tintin.mapper.UserMapper">

    <select id="listUser" resultType="com.tintin.entry.User">
        select * from mybatis.user
    </select>

    <select id="getUserById" resultType="com.tintin.entry.User">
        select id, name, pwd from mybatis.user where id = #{id}
    </select>

    <insert id="addUser" parameterType="com.tintin.entry.User">
        insert into mybatis.user (id, name, pwd) value(#{id}, #{name}, #{pwd})
    </insert>

    <update id="updateUserById" parameterType="com.tintin.entry.User">
        update mybatis.user set name=#{name}, pwd=#{pwd} where id=#{id}
    </update>

    <delete id="delUserById" parameterType="java.lang.Integer">
        delete from mybatis.user where id = #{id}
    </delete>
</mapper>
Map传参(模糊查询)
<select id="getUserLike" parameterType="map" resultType="com.tintin.entry.User">
        select id, name, pwd from mybatis.user where name like "%"#{name}"%"
</select>

6.测试

@Test
public void Test01(){
  SqlSession sqlSession = MybatisUtil.getSqlSessionFactory();
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  List<User> users = mapper.listUser();

  for (User user : users) {
    System.out.println(user);
  }
}

属性

1.引入properties

在这里插入图片描述
在这里插入图片描述

2.类型别名(typeAliases)

方法一:指定到具体的类,可以自定义别名
<typeAliases>
        <typeAlias alias="UserEntry" type="com.tintin.entry.User"/>
</typeAliases>
<select id="listUser" resultType="UserEntry">
        select * from mybatis.user
</select>
方法二:指定到包
<typeAliases>
        <package name="com.tintin.entry"/>
</typeAliases>
<select id="listUser" resultType="user">
        select * from mybatis.user
</select>

映射器(mapper)

<mappers>
  //方法一:指定到具体的xml文件
  <mapper resource="com/tintin/mapper/xml/UserMapper.xml"/>
  //方法二:指定到接口 接口名字和xml文件名字必须相同,且在同一包下
  <mapper class="com.tintin.mapper.UserMapper"/>
  //方法三:指定到包  接口名字和xml文件名字必须相同,且在同一包下
  <package name="com.tintin.mapper"/>
</mappers>

ResultMapper(数据库字段和属性名不同)

<!--结果集映射-->
<resultMap id="myMap" type="User">
  <!--column(列):数据库表中的字段,property(属性):实体类的属性-->
  <result column="pwd" property="password"/>
  <result column="name" property="UserName"/>
</resultMap>

<select id="getUserById" resultMap="myMap">
  select * from mybatis.user where id = #{id};
</select>

多对一

(association)

方法一:

<select id="getAllStu2" resultMap="StudentTeacher2">
    select s.id sId,s.name sName,t.name tName
        from student s
        LEFT JOIN teacher t on s.tid = t.id
</select>
<!-- 将查询的结果,嵌套映射在不同的实体类上 -->
<resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="sId"/>
    <result property="name" column="sName"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tName"/>
    </association>
</resultMap>

方法二:

<!--
  思路:
      1.查询所有的学生信息
      2.根据查询出来的学生的tid,寻找对应的老师! 子查询
-->
<select id="getAllStu" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--  
            复杂的属性,需要单独处理
              对象:association     集合:collection
     -->
    <association property="teacher" column="tid" javaType="Teacher" select="getAllTeacher"/>
</resultMap>

<select id="getAllTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

一对多

(collection)

方法一:

<!-- 先查询出来结果,再映射到集合中 -->
<select id="getTeacherById" resultMap="TeacharStudent">
    select t.id tId,t.name tName,s.id sId,s.name sName
        from teacher t 
        LEFT JOIN student s on t.id = s.tid
        where t.id = #{tId}
</select>

<resultMap id="TeacharStudent" type="Teacher">
    <result column="tId" property="id"/>
    <result column="tName" property="name"/>

    <!--集合中的泛型信息,通过ofType获取-->
    <collection property="studentList" ofType="Student">
        <result column="sId" property="id"/>
        <result column="sName" property="name"/>
    </collection>
</resultMap>

方法二:

<!-- 通过集合,进行关联查询 -->
<select id="getTeacherById2" resultMap="TeacharStudent2">
    select * from teacher where id = #{tId}
</select>

<resultMap id="TeacharStudent2" type="Teacher">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <collection  property="studentList" javaType="ArrayList" ofType="Student" select="selectStuByTid" column="id"/>
</resultMap>

<select id="selectStuByTid" resultType="Student">
    select * from student where tid = #{id}
</select>

日志

1.引入包

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2.log4j.properties 配置模板

log4j.rootLogger=DEBUG, console, dailyFile, im
log4j.additivity.org.apache=true
# 控制台(console)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 日志文件(logFile)
log4j.appender.logFile=org.apache.log4j.FileAppender
log4j.appender.logFile.Threshold=DEBUG
log4j.appender.logFile.ImmediateFlush=true
log4j.appender.logFile.Append=true
log4j.appender.logFile.File=D:/logs/log.log4j
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 回滚文件(rollingFile)
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.Threshold=DEBUG
log4j.appender.rollingFile.ImmediateFlush=true
log4j.appender.rollingFile.Append=true
log4j.appender.rollingFile.File=D:/logs/log.log4j
log4j.appender.rollingFile.MaxFileSize=200KB
log4j.appender.rollingFile.MaxBackupIndex=50
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 定期回滚日志文件(dailyFile)
log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyFile.Threshold=DEBUG
log4j.appender.dailyFile.ImmediateFlush=true
log4j.appender.dailyFile.Append=true
log4j.appender.dailyFile.File=D:/logs/log.log4j
log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd
log4j.appender.dailyFile.layout=org.apache.log4j.PatternLayout
log4j.appender.dailyFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 应用于Socket
log4j.appender.socket=org.apache.log4j.RollingFileAppender
log4j.appender.socket.RemoteHost=localhost
log4j.appender.socket.Port=5001
log4j.appender.socket.LocationInfo=true
# Set up for Log Factor 5
log4j.appender.socket.layout=org.apache.log4j.PatternLayout
log4j.appender.socket.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Log Factor 5 Appender
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000
# 发送日志到指定邮件
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
log4j.appender.mail.Threshold=FATAL
log4j.appender.mail.BufferSize=10
log4j.appender.mail.From = xxx@mail.com
log4j.appender.mail.SMTPHost=mail.com
log4j.appender.mail.Subject=Log4J Message
log4j.appender.mail.To= xxx@mail.com
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 应用于数据库
log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.database.URL=jdbc:mysql://localhost:3306/test
log4j.appender.database.driver=com.mysql.jdbc.Driver
log4j.appender.database.user=root
log4j.appender.database.password=
log4j.appender.database.sql=INSERT INTO LOG4J (Message) VALUES('=[%-5p] %d(%r) --> [%t] %l: %m %x %n')
log4j.appender.database.layout=org.apache.log4j.PatternLayout
log4j.appender.database.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
 
# 自定义Appender
log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
log4j.appender.im.host = mail.cybercorlin.net
log4j.appender.im.username = username
log4j.appender.im.password = password
log4j.appender.im.recipient = corlin@cybercorlin.net
log4j.appender.im.layout=org.apache.log4j.PatternLayout
log4j.appender.im.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n

3.最后需要在mybatis-config.xml中配置

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

日志等级:debug 、info 、warning 、error 、critical 默认的是WARNING

分页

1.limit分页

<select id="getUserByPage" parameterType="map" resultType="user">
        select id,name,pwd from mybatis.user limit #{pageStart}, #{pageEnd}
</select>

2.RowBounds分页

3.分页插件

注解开发

@Select("select * from user")
List<User> getUsers();
<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>

Mybatis执行过程

执行流程

动态SQL

1.IF

//select id, name, pwd from user where 1=1 and name like "%"?"%" and name like "%"?"%"

<select id="getByNameLike" resultType="user" parameterType="map">
  
        select id, name, pwd from user where 1=1

        <if test="name != null">
            and name like "%"#{name}"%"
        </if>

        <if test="pwd != null">
            and name like "%"#{pwd}"%"
        </if>

</select>

2.choose、when、otherwise

在choose中判断是否满足条件,当满足一个条件时,下面语句不会继续执行,都不满足时,拼接otherwise内容
<select id="getByNameOrPwd" parameterType="map" resultType="user">
        select id, name, pwd from user
        <choose>
                        //条件一
            <when test="name != null">
                where name = #{name}
            </when>
                        //条件二
            <when test="pwd != null">
                where pwd = #{pwd}
            </when>
                        //都不满足
            <otherwise>
                where id = 1
            </otherwise>

        </choose>
    </select>

3.trim、where、set

//where标签自动补充where
<select id="getByNameAndPwd" parameterType="map" resultType="user">
        select id, name, pwd from user
        <where>

            <if test="name != null">
                name = #{name}
            </if>

            <if test="pwd != null">
                and pwd = #{pwd}
            </if>

        </where>
    </select>
-- 指定sql片段以 where 开始,如果where 后面紧跟 (and、or),则被删除
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
-- set元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

4.foreach

<select id="getByIds" parameterType="map" resultType="user">

        select id, name, pwd from user
        <where>
            <foreach collection="ids" item="id" open="(" separator="or"  close=")">
                id = #{id}
            </foreach>
        </where>

</select>

5.SQL片段

<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

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

缓存

https://img-blog.csdnimg.cn/9db72c8d64da45bf8a2d649ce764981b.png# Mybatis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值