MyBatis基本使用

1. mybatis基本使用

官网文档: https://mybatis.org/mybatis-3/zh/getting-started.html

pom.xml

 <!--导入依赖-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

src/main/resources

<?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="com.mysql.jdbc.Driver"/>
                <property name="url" 
                          value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="hdk123"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

编写代码

  • 实体类

    src/main/java

package cn.mldn.lxh.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;
    private String userName;
    private String passWord;
    private String email;
    private Date birthDay;

}

  • Mapper接口
package cn.mldn.lxh.mapper.impl;

import cn.mldn.lxh.bean.User;
import java.util.List;

public interface IUserMapper {
    Integer insert(User user)throws Exception;

    Integer deleteId(Integer id)throws Exception;

    Integer deleteName(String name)throws Exception;

    Integer updateId(User user)throws Exception;

    Integer updateName(User user)throws Exception;

    User findById(Integer id)throws Exception;

    User findByName(String name)throws Exception;

    List<User> findAll()throws Exception;
}

  • 接口实现类
<?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">
<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.hou.dao.UserDao">

    <!--id方法名-->
	<insert id="insert" parameterType="cn.mldn.lxh.bean.User" useGeneratedKeys="true"
        keyProperty="id" keyColumn="id">
        insert into t_user values(default ,#{userName},#{passWord},#{email},#{birthDay})
    </insert>

    <delete id="deleteId" parameterType="integer">
        delete from t_user where id = #{id}
    </delete>

    <delete id="deleteName" parameterType="string">
       delete from t_user where username = #{userName}
    </delete>

    <update id="updateId" parameterType="cn.mldn.lxh.bean.User">
        update t_user
        set username = #{userName},password = #{passWord},email = #{email},
        birthday = #{birthDay}
        where id = #{id}
    </update>

    <update id="updateName" parameterType="cn.mldn.lxh.bean.User">
        update t_user
        set password = #{passWord},email = #{email},birthday = #{birthDay}
        where username = #{userName}
    </update>

    <select id="findById" parameterType="integer" resultType="cn.mldn.lxh.bean.User">
        select * from t_user where id = #{id}
    </select>

    <select id="findByName" parameterType="string" resultType="cn.mldn.lxh.bean.User">
        select * from t_user where username = #{userName}
    </select>

    <select id="findAll" resultType="cn.mldn.lxh.bean.User">
        select * from t_user;
    </select>

</mapper>

src/main/java

package com.hou.utils;

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;

// mybatis工具类
public class MybatisUtils {

    private static SqlSessionFactory sessionFactory = null;

    static {
        try {
            InputStream stream = null;
            //1 读取配置文件,将文件读成流的形式
            stream = Resources.getResourceAsStream("mybatis-config.xml");
            //2 创建一个SqlSessionFactory(工厂)
            sessionFactory = new SqlSessionFactoryBuilder().build(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    public static SqlSession getSqlSession(){
        //openSession(true)		表示不开启mybatis内置事务,默认开启
        return sessionFactory.openSession();
    }

}

测试

注意点:

package cn.mldn.lxh.mapper;

import cn.mldn.lxh.bean.User;
import cn.mldn.lxh.mapper.impl.IUserMapper;
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 org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.InputStream;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class IUserMapperTest {

    @Test
    public void findAll() throws Exception {
        // 利用mybatis向数据库查询所有User用户
        //1 读取配置文件,将文件读成流的形式
       	/**
        InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");

        //2 创建一个SqlSessionFactory(工厂)
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);

        //3 创建一个SqlSession(工具,它是我们最重要的一个API,基于它可以完成对数据库的CRUD操作)
        SqlSession sqlSession = sqlSessionFactory.openSession();
		**/
        
        // 从MybatisUtils工具类中获取SqlSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
        //4 完成查询操作(根据mapper.xml文件进行查询)
        //第一个参数:命名空间.statemnetId  表示这唯一一条sql语句
//        List<User> userList = sqlSession.selectList("UserMapper.findAll");
        
		//根据mapper接口进行查询
        IUserMapper iUserMapper = sqlSession.getMapper(IUserMapper.class);

        List<User> userList = iUserMapper.findAll();
        // 打印结果
        userList.forEach(user -> System.out.println(user));

        //5 提交事务(Mybatis默认不会自动提交事务)
        sqlSession.commit();

        //6 关闭资源
        sqlSession.close();
    }
}

(mybatis核心配置文件)

mybatis-config.xml文件

<?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">
            <!--            开启mybatis内置事务-->
            <transactionManager type="JDBC"/>
            <!--            mybatis内置数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="hdk123"/>
            </dataSource>
        </environment>
    </environments>

    <!--每一个mapper.xml都需要注册-->
    <mappers>
        <mapper resource="com/hou/dao/UserMapper.xml"/>
    </mappers>

</configuration>

在pom.xml中加入

<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

开发步骤

  1. 导入包
  2. 配置数据库
  3. 建造工具类
SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

SqlSession

每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。 下面的示例就是一个确保 SqlSession 关闭的标准模式

2. 增删改查(crud参考)

1. namespace

namespace中的包名要和接口一致

2. select

  • id:就是对应的namespace的方法名
  • resultType:sql语句的返回值!
  • parameterType: 参数类型!
  1. 编写接口
  2. 编写对应的mapper中的对应语句
  3. 测试
UserMapper
package com.hou.dao;

import com.hou.pogo.User;
import java.util.List;

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();

    //根据id查询用户,@Param("id")用于指定mapper.xml文件中所使用的参数名
    User getUserById(@Param("id") int id);

    //插入用户
    void addUser(@Param("user")User user);

    //修改用户
    int updateUser(@Param("user")User user);

    //删除用户
    int deleteUser(@Param("id")int id);
}
UserMapper.xml
<?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">
<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.hou.dao.UserMapper">
    
    <!-- 返回主键ID
		id:方法名
		parameterType:映射实体类  => 对象中的属性可以直接取出来
		# 注解:添加成功返回生成的ID必须设置一下两个属性
		useGeneratedKeys:添加成功后,返回数据库生成的主键ID
		keyProperty:返回的ID,对应实体类的主键-->
    <insert id="addUser" parameterType="com.hou.pogo.User" useGeneratedKeys="true" keyProperty="id">
        insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd});
    </insert>
    
	<insert id="saveReturnId" parameterType="com.hopu.domain.User">
   <!-- 返回主键ID, => 推荐使用
		keyColumn 指定主键列名称
        keyProperty 指定主键封装到实体的哪个属性
        resultType 指定主键类型
        order 指定在数据插入数据库前(后),执行此语句 -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            <!-- 返回最后一条插入语句的主键ID -->
            select last_insert_id()
        </selectKey>
        insert into t_user(user_name,password,email,birthday)
        values (#{username},#{password},#{email},#{birthday});
    </insert>
    
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
    </delete>

    <update id="updateUser" parameterType="com.hou.pogo.User">
        update mybatis.user set name=#{name}, pwd=#{pwd} where id =#{id};
    </update>
    
    <!--id:方法名
		resultType:返回的类型
		parameterType:传入的参数类型-->
    <select id="getUserById" resultType="com.hou.pogo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

    <select id="getUserList" resultType="com.hou.pogo.User">
        select * from mybatis.user
    </select>

</mapper>
Test
package com.hou.dao;

import com.hou.pogo.User;
import com.hou.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userDao.getUserList();

            // method 2
//        List<User> userList = sqlSession.selectList("com.hou.dao.UserDao.getUserList");

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

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }

    }

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    //增删改需要提交事务
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(5,"hou","123456"));

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"hou","123"));

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(5);

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}

注意点:增删改需要提交事务。

3. Map

假如我们的实体类属性过多,用map,传递map的key

<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id, name, pwd) values (#{id1}, #{name1}, #{pwd1});
</insert>

int addUser2(Map<String, Object> map); 		// 接口方法
    
@Test							//	测试
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id1",5);
    map.put("name1","dong");
    map.put("pwd1","12345");
    mapper.addUser2(map);

    //提交事务
    sqlSession.commit();
    sqlSession.close();
}

4.模糊查询

java代码执行的时候,传递通配符%

<select id="getUserLike" resultType="com.hou.pogo.User">
    select * from mybatis.user where name like #{value}
</select>


@Test
public void getUserLike(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> list = mapper.getUserLike("%o%");

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

    sqlSession.close();
}

3. 配置解析

1. 核心配置文件

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

2. 环境配置(environments)

MyBatis 可以配置成适应多种环境

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

Mybatis 默认的事务管理器是JDBC,另外是MANAGED

MyBatis的数据库连接方式POOLED、UNPOOLED和JNDI,默认为POOLED

3. 属性

我们可以通过properties属性来引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。 (jdbc.properties)

编写一个配置文件

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.56.106:3306/mybatis?serverTimezone=Asia/Shanghai&userSSL=true&userUnicode=true&characterEncoding=UTF-8
jdbc.user=root
jdbc.pass=123456

在核心配置文件中引入

mybatis-config.xml (同时有的话,优先走外面properties)

<?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>

    <!--引入外部配置文件-->
    <properties resource="jdbc.properties"/>
    
    <settings>
        <!-- 开启mybatis日志 -->
        <setting name="logImpl" value="LOG4J2"/>
        <!-- 开启驼峰命名规则 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
    <!--    类别名-->
    <typeAliases>
        <package name="cn.mldn.lxh"/>
    </typeAliases>

    <!-- development : 开发模式
         work : 工作模式      -->
    <environments default="development">
        <environment id="development">
            <!-- 开启mybatis内置的事务管理 --> 
            <transactionManager type="JDBC"/>
            <!-- 配置mybatis内置数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.pass}"/>
            </dataSource>
        </environment>
    </environments>

    <!--每一个mapper.xml都需要注册-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

</configuration>

4. 类型别名(typeAliases)

类型别名可为 Java 类型设置一个缩写名字。

<typeAliases>
    <typeAlias type="com.hou.pogo.User" alias="User"></typeAlias>
</typeAliases>

扫描实体类的包,默认别名就为这个类的类名首字母小写

<typeAliases>
    <package name="com.hou.pogo"></package>
</typeAliases>

在实体类,比较少的时候使用第一种,实体类多使用第二种。

第一种可以自定义,第二则不行,但是 若有注解,则别名为其注解值 。

@Alias("hello")
public class User {
}

5. 设置

设置名描述有效值默认值
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true | falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true | falsefalse
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未设置
mapUnderscoreToCamelCase使用驼峰命名法转换字段true | falsefalse

6. 其他

7. 映射器 => 映射mapper.xml文件

方式一: [推荐使用]

<mappers>
    <mapper resource="com/hou/dao/UserMapper.xml"/>
</mappers>

方式二:

<mappers>
    <mapper class="com.hou.dao.UserMapper" />
</mappers>
  • 接口和它的Mapper必须同名
  • 接口和他的Mapper必须在同一包下

方式三:

<mappers>
    <package name="com.hou.dao" />
</mappers>
  • 接口和它的Mapper必须同名
  • 接口和他的Mapper必须在同一包下

8.生命周期和作用域

作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了 。
  • 局部变量

SqlSessionFactory

  • 就是数据库连接池。
  • 一旦被创建就应该在应用的运行期间一直存在 ,没有任何理由丢弃它或重新创建另一个实例 。 多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。

SqlSession

  • 每个线程都应该有它自己的 SqlSession 实例。
  • 连接到连接池的请求!
  • SqlSession 的实例不是线程安全的,因此是不能被共享的 ,所以它的最佳的作用域是请求或方法作用域。
  • 用完之后赶紧关闭,否则资源被占用。

4. 解决属性名和字段名不一致的问题

数据库中的字段

新建一个项目,拷贝之前,测试实体字段不一致的情况

User

package com.hou.pogo;

public class User {

    private int id;
    private String name;
    private String password;
}

问题:

User{id=2, name=‘wang’, password=‘null’}

解决方法:

核心配置文件

  • 起别名
<select id="getUserById" resultType="User"
    parameterType="int">
        select id,name,pwd as password from mybatis.user where id = #{id}
</select>
  • resultMap 结果集映射
<?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">
<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.hou.dao.UserMapper">

    <select id="getUserById" resultMap="UserMap" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--colunm 数据库中的字段,property实体中的属性-->
        <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>

</mapper>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
<resultMap id="UserMap" type="User">
    <!--colunm 数据库中的字段,property实体中的属性-->
    <!--<result column="id" property="id"></result>-->
    <!--<result column="name" property="name"></result>-->
    <result column="pwd" property="password"></result>
</resultMap>

5. 日志

1. 日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手。

曾经:sout,debug

现在:日志工厂

logImpl

  • SLF4J
  • LOG4J [掌握]
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING [掌握]
  • NO_LOGGING

具体使用哪一个,在设置中设定

STDOUT_LOGGING 标志日志输出

mybatis-confi中

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

2. Log4j

  1. 先导包

    pom.xml下

     <!--        日志支持  -->
                <dependency>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-core</artifactId>
                    <version>2.13.3</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                    <version>2.13.3</version>
                </dependency>
    
  2. 新建log4j2.properties文件

# 设定Log4j2内部的日志级别,有效值:trace, debug, info, warn, error, fatal。只对Log4j本身的事件有效,可以不设置,当设置成trace时,会看到log4j2内部各种详细输出
status = fatal

# 配置的名称
name =PropertiesConfig
# 日志输出的位置,console 控制台,I 文件
appenders = console

#控制台类型的日志输出源
appender.console.type = Console
#输出源的名称
appender.console.name = consoleLog
#输出布局类型
appender.console.layout.type = PatternLayout
#输出模板
appender.console.layout.pattern = %-d{yyyy-MM-dd HH:mm:ss} [%p] [%c] [%M:%L] %m%n
appender.console.target = System_out 

# 文件滚动记录类型的日志输出源
appender.I.type = RollingFile
# 当前滚动输出源的名称,以便在Logger的配置项中能够调用
appender.I.name = InfoRollingFile
# 当前正在操作的日志文件的文件名
appender.I.fileName = ${web:rootDir}/WEB-INF/log/info.log
# 归档后的日志文件的文件名格式,其中`%d{yyyy-MM-dd-HH}`用来自动填充日期
appender.I.filePattern = ${web:rootDir}/WEB-INF/log/info_%d{MM-dd}_%i.log
# 滚动记录输出源布局类型
appender.I.layout.type = PatternLayout
# 滚动记录输出模板
appender.I.layout.pattern = %-d{yyyy-MM-dd HH:mm:ss} [%p] [%c] %m%n
# 指定记录文件的封存策略,该策略主要是完成周期性的日志文件封存工作
appender.I.policies.type = Policies
# 基于时间进行日志的切割
appender.I.policies.time.type = TimeBasedTriggeringPolicy
# 切割的间隔为1月, 即每天进行一次日志的归档,如果filePattern中配置的文件重命名规则是${web:rootDir}/WEB-INF/log/info_%d{yyyy-MM-dd HH-mm}-%i,最小的时间粒度是mm,即分钟,TimeBasedTriggeringPolicy指定的size是1,结合起来就是每2分钟生成一个新文件。如果改成%d{yyyy-MM-dd HH},最小粒度为小时,则每2个小时生成一个文件。
appender.I.policies.time.interval = 1
# 修正时间范围, 从0时开始计数。若modulate=true,则封存时间将以0点为边界进行偏移计算。比如,modulate=true,interval=4hours,那么假设上次封存日志的时间为03:00,则下次封存日志的时间为04:00,之后的封存时间
appender.I.policies.time.modulate = true
# 基于日志文件体积的触发策略
appender.I.policies.size.type = SizeBasedTriggeringPolicy
# 当日志文件体积大于size指定的值时,触发Rolling
appender.I.policies.size.size=50M
# 文件封存的覆盖策略(RolloverStrategy)
appender.I.strategy.type = DefaultRolloverStrategy
# 生成分割(封存)文件的个数
appender.I.strategy.max = 100

# 根日志,所有日志的父节点 级别顺序(低到高):all < trace <debug < info < warn < error < fatal <off
rootLogger.level = debug
rootLogger.appenderRef.I.ref = InfoRollingFile
rootLogger.appenderRef.I.level = off

# 关联名称为consoleLog的输出源 注意consolelog小写
rootLogger.appenderRef.consolelog.ref = consoleLog
# 生产环境设为off关闭控制台日志输出,开启debug,mybatis才能输出日志
rootLogger.appenderRef.consolelog.level = debug
  1. 配置实现
<settings>
    <setting name="logImpl" value="LOG4J"/>
</settings>
  1. Log4j使用
package com.hou.dao;

import com.hou.pojo.User;
import com.hou.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;

public class UserDaoTest {

    static Logger logger = Logger.getLogger(UserDaoTest.class);

    @Test
    public void test(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            logger.info("测试");
            User user = userDao.getUserById(2);
            System.out.println(user);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void testLog4j(){
        logger.info("info:进入了testlog4j");
        logger.debug("debug:进入了testlog4j");
        logger.error("error:进入了testlog4j");
    }

}

6. 分页

1. Limit 分页

语法:

SELECT * from user limit pageNum,pageSize;
SELECT * from user limit 0,2;			//   查询第一页,  每页显示两条数据	

当前页号:pageNum
页面显示数量:pageSize
首记录索引:firstIndex = (pageNum-1) * pageSize
总记录数:totalRecordCount = select count(*) from 表
总页数:totalPage = totalRecordCount-1/pageSize-1     

2. RowBounds分页

@Test

@Test
public void getUserByRow(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //RowBounds实现
    RowBounds rowBounds = new RowBounds(1, 2);

    //通过java代码层面
    List<User> userList = sqlSession.selectList
        ("com.hou.dao.UserMapper.getUserByRowBounds",
         null,rowBounds);

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

    sqlSession.close();
}

3. pageHelper分页插件

1、导入依赖

			 <!--mybatis分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.10</version>
            </dependency>

2、添加mybatis-config.xml配置

<plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用MySQL方言的分页 -->
            <property name="helperDialect" value="mysql"/><!--如果使用mysql,这里value为mysql-->
            <property name="pageSizeZero" value="true"/>
        </plugin>
</plugins>

3、使用分页插件

//        设置分页的属性,注意:此条语句会影响此语句下的,第一条查询语句,会将这条语句变为分页查询
        PageHelper.startPage(1, 4);
//        在PageHelper的影响下,从mapper接口获取分页的数据
        List<Books> all = iBooksMapper.findAll();
//        将获取到的分页数据放入pageInfo中,来构建pageInfo对象,此类中有分页常用的属性
        PageInfo<Books> pageInfo = new PageInfo<Books>(all);

PageInfo类中的各参数涵义

    private int pageNum;		//当前页
    private int pageSize;		//每页的数量
    private int size;			//当前页的数量
    private int startRow;		//当前页面第一个元素在数据库中的行号
    private int endRow;			//当前页面最后一个元素在数据库中的行号
    private long total;			//总记录数
    private int pages;			//总页数
    private List<T> list;		//结果集(每页显示的数据)
    private int firstPage;		//第一页
    private int prePage;		//前一页
    private boolean isFirstPage = false;		//是否为第一页
    private boolean isLastPage = false;			//是否为最后一页
    private boolean hasPreviousPage = false;	//是否有前一页
    private boolean hasNextPage = false;		//是否有下一页
    private int navigatePages;					//导航页码数
    private int[] navigatepageNums;				//所有导航页号

4、tk-Mybatis插件

7. 使用注解开发

  1. 删除 UserMapper.xml

  2. UserMapper

    package com.hou.dao;
    
    import com.hou.pojo.User;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    public interface UserMapper {
    
        @Select("select * from user")
        List<User> getUsers();
    }
    
  3. 核心配置 mybatis-config.xml

    <?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>
    
        <!--引入外部配置文件-->
        <properties resource="db.properties"/>
    
        <!--可以给实体类起别名-->
        <typeAliases>
            <typeAlias type="com.hou.pojo.User" alias="User"></typeAlias>
        </typeAliases>
    
        <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 class="com.hou.dao.UserMapper"></mapper>
        </mappers>
    </configuration>
    

    本质:反射机制

    底层:动态代理!

Mybatis详细执行流程:

  1. Resource获取全局配置文件
  2. 实例化SqlsessionFactoryBuilder
  3. 解析配置文件流XMLCondigBuilder
  4. Configration所有的配置信息
  5. SqlSessionFactory实例化
  6. trasactional事务管理
  7. 创建executor执行器
  8. 创建SqlSession
  9. 实现CRUD
  10. 查看是否执行成功
  11. 提交事务
  12. 关闭

注解CRUD

package com.hou.dao;

import com.hou.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    //方法存在多个参数,所有的参数必须加@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id);

    @Insert("insert into user (id, name, pwd) values(#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name=#{name}, pwd=#{password} where id=#{id}")
    int updateUser(User user);

    @Delete("delete from user where id=#{id}")
    int deleteUser(@Param("id") int id);

}

MybatisUtile

package com.hou.utils;

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;

//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //使用mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

}

Test

package com.hou.dao;

import com.hou.pojo.User;
import com.hou.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userDao.getUsers();
            for (User user : userList) {
                System.out.println(user);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void getuserById(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            User user = userDao.getUserById(1);

            System.out.println(user);


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void addUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.addUser(new User(6, "kun","123"));

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void updateUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.updateUser(new User(6, "fang","123"));

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }

    @Test
    public void deleteUser(){
        // 获得sqlsession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            // 1.执行 getmapper
            UserMapper userDao = sqlSession.getMapper(UserMapper.class);
            userDao.deleteUser(6);

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭
            sqlSession.close();
        }
    }
}

9. 一对一

  • 多个学生关联一个老师(多对一)
  • 集合(一对多)

1. 建表

CREATE TABLE `teacher` (
	`id` INT(10) NOT NULL PRIMARY KEY,
	`name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher (`id`, `name`) VALUES (1, 'hou');

CREATE TABLE `student` (
	`id` INT(10) NOT NULL,
	`name` VARCHAR(30) DEFAULT NULL,
	`tid` INT(10) DEFAULT NULL,
	PRIMARY KEY (`id`),
	KEY `fktid` (`tid`),
	CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO student (`id`, `name`, `tid`) VALUES (1, 'xiao1', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (2, 'xiao2', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (3, 'xiao3', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (4, 'xiao4', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (5, 'xiao5', 1);
  1. 新建实体类

    package com.hou.pojo;
    
    import lombok.Data;
    
    @Data
    public class Student {
        private int id;
        private String name;
    
        //学生需要关联一个老师
        private Teacher teacher;
    }
    
    package com.hou.pojo;
    
    import lombok.Data;
    
    @Data
    public class Teacher {
        private int id;
        private String name;
    }
    
  2. 建立Mapper接口

  3. 建立Mapper.xml

  4. 测试是否能够成功

2. 按照查询嵌套处理(association属性)

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.hou.dao.StudentMapper">

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

    <resultMap id="StudentTeacher" type="com.hou.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--对象使用assiociation-->
        <!--集合用collection-->
        <!-- 注意:这里不是根据外键进行查询的,而是通过指定实体类,根据实体类查询指定的表,
			property: 设置主对象,中的子对象
 			javaType: 指定查询的表的实体类对象
			column:	tid表示studnet表中关联的teacher 表 id 然后根据id查询teacher
			select: 关联的查询,根据此查询返回指定的数据-->
        <association property="teacher" 
                     column="tid" 
                     javaType="com.hou.pojo.Teacher"
                     select="getTeacher"/>
    </resultMap>
	<!-- 注意:此方法不需要在mapper接口中进行注册,直接在xml文件中使用即可 -->
    <select id="getTeacher" resultType="com.hou.pojo.Teacher">
        <!--#{id}  此处的id是tid字段传递过来的-->
      select * from teacher where id = #{id};
    </select>

</mapper>

3. 按照结果嵌套处理

select s.id sid,s.name sname,t.name tname  from student s,teacher t where s.tid=t.id;
<!--上面是:查询的语句,下面是在程序中实现功能-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname
    from student s,teacher t where s.tid=t.id;
</select>

<resultMap id="StudentTeacher2" type="com.hou.pojo.Student">
    <result property="id" column="sid"></result>
    <result property="name" column="sname"></result>
    <association property="teacher" javaType="com.hou.pojo.Teacher">
        <result property="name" column="tname"></result>
    </association>
</resultMap>

4、基于注解

    @Select("select * from person where pid = #{pid}")
    @Results({
            @Result(id=true,column="pid",property="pid"),
            @Result(column="pname",property="pname"),
            @Result(column="page",property="page"),
		@Result(column="pid",property="card",one=@One(select="com.desert.dao.ICardDao.getCard",fetchType= FetchType.EAGER))
    })
   public Person getPerson(int pid);

property 映射到列结果的字段或属性。

column 数据库中的列名,或者是列的别名。

10. 一对多

一个老师拥有多个学生

对于老师而言就是一对多

1.环境搭建

实体类

package com.hou.pojo;

import lombok.Data;
import java.util.List;

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> studentList;
}
package com.hou.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

2. 按照查询嵌套处理(collection属性)

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{id}
</select>

<resultMap id="TeacherStudent2" type="com.hou.pojo.Teacher">
        <!--对象使用assiociation-->
        <!--集合用collection-->
    	<!-- 根据teacher id 查询学生关联的老师的数据 -->
    <collection property="studentList" 
                column="id" 
                javaType="ArrayList"
                select="getStudentByTeacherId"></collection>
</resultMap>

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

3. 按照结果查询

<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 = #{id};
</select>

<resultMap id="TeacherStudent" type="com.hou.pojo.Teacher">
    <result property="id" column="tid"></result>
    <result property="name" column="tname"></result>
 
    <!--集合中的泛型信息,我们用oftype获取-->
    <collection property="studentList" ofType="com.hou.pojo.Student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
    </collection>
</resultMap>

基于注解

    @Select("select * from provinces where pid = #{pid}")
    @Results({
            @Result(id=true,column="pid",property="pid"),
            @Result(column="pname",property="pname"),
            @Result(column="pid",property="citysSet",
                    many=@Many(
                            select="com.desert.dao.ICityDao.getCitybypid",
                            fetchType= FetchType.LAZY
                    )
            )
    })
    public Provinces getProvincesByid(int pid);

小结

  1. 关联 - association 多对一
  2. 集合 - collection 一对多
  3. javaType & ofType
    1. JavaType用来指定实体中属性类型
    2. ofType映射到list中的类型,泛型中的约束类型

注意点:

  • 保证sql可读性,尽量保证通俗易懂
  • 注意字段问题
  • 如果问题不好排查错误,使用日志

11. 动态sql(重点)

动态sql:根据不同的条件生成不同的SQL语句

1. 搭建环境

核心配置

<settings>
    <!-- 使用驼峰命名法转换字段。 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

2. if (条件查询)

满足条件即添加,sql条件

<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != author">
            and author = #{author}
        </if>
    </where>
</select>

test

@Test
public void queryBlogIF(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();

    //        map.put("title", "second");
    map.put("author", "houdongun");

    List<Blog> list = blogMapper.queryBlogIF(map);

    for (Blog blog : list) {
        System.out.println(blog);
    }

    sqlSession.close();
}

3. choose (分支条件)

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql

<select id="queryBlogchoose" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <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>

4. trim,where、set

trim标签是一个格式化标签,可以完成set或者是where的功能。

1、使用trim代替where
    <!-- 5、trim标签,替换where
        <trim>标签属性说明:
        prefix:在代码块之前加点什么内容;
		suffix:在代码块后加点什么内容;
        prefixOverrides:在代码块之前去掉什么多余的内容;
		suffixOverrides:在代码之后去掉什么多余的内容。
     -->
    <select id="findByConditions" resultMap="userMap">
        select * from t_user
        <trim prefix="where" prefixOverrides="and|or">
            <if test="username !=null and username !=''">
                and user_name=#{username}
            </if>
            <if test="email !=null and email !=''">
                and email=#{email}
            </if>
        </trim>
    </select>
2、使用trim代替set
    <!-- trim代替set -->
    <update id="update" parameterType="com.hopu.domain.User">
        update t_user
        <trim prefix="set" suffixOverrides=",">
            <if test="username !=null and username !=''">
                user_name=#{username}
            </if>
            <if test="password !=null and password !=''">
                password=#{password}
            </if>
            <if test="email !=null and email !=''">
                email=#{email}
            </if>
            <if test="birthday !=null and birthday !=''">
                birthday=#{birthday}
            </if>
        </trim>
        where id=#{id}
    </update>

SQL片段

有些时候我们有一些公共部分

  1. 使用sql便签抽取公共部分
  2. 在使用的地方使用include标签
<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>

注意:

  • 最好基于单表
  • sql里不要存在where标签

5. for-each

<!--
	collection:数据源【重点关注这一项,它的值会根据出入的参数类型不同而不同】 
----1、当参数为一个集合时,此值为collection,如果参数是List,此值也可以使用list代替】 
----2、当参数为一个数组时,此值为array
----3、当参数是一个pojo时,此值为pojo对应的属性名。这种情况,不能使用@Param("自定义")。
----4、特殊:此处的值也可以通过@Param("自定义")的方式在Dao层方法上自己指定。
	ids是传的,#{id}是遍历的
	open:开始遍历之前的拼接字符串 
	close:结束遍历之后的拼接字符串 
	separator:每次遍历之间的分隔符 
	item:每次遍历出的数据 
	index:遍历的次数,从0开始 
-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from mybatis.blog where id in
      <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
      </foreach>
</select>

test

@Test
public void queryBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();

    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(3);
    map.put("ids",ids);

    List<Blog> list = blogMapper.queryBlogForeach(map);

    for (Blog blog : list) {
        System.out.println(blog);
    }

    sqlSession.close();
}

12. 缓存(了解)

1. 一级缓存

一级缓存默认开启,不能关闭,并且只在一次sqlseesion中有效

说明:

  • 同一个sqlSession中两次执行相同的sql语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),
  • 第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。
  • 当一个sqlSession结束后该sqlSession中的一级缓存也就不存在了。
  • 不同的sqlSession之间的缓存数据区域(HashMap)是互相不影响的。

注意:

  • 调用SqlSession的clearCache(),或者执行C(增加)U(更新)D(删除)操作,都会清空缓存。
  • 查询语句中这样的配置< select flushCache=“true”/>也会清除缓存。

一级缓存是基于sqlSession,同一个sqlSession执行的语句,才能利用到缓存。

2. 二级缓存

二级缓存是sqlSessionFactory级别的缓存,是默认开启,但是可以关闭的。

<!-- 默认开启可以不用配置 -->
<setting name="cacheEnabled" value="true"/>

在当前mapper.xml中使用二级缓存
在这里插入图片描述

test

@Test
public void test(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    SqlSession sqlSession1 = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.queryUserByid(1);
    System.out.println(user);
    sqlSession.close();

    UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
    User user1 = userMapper1.queryUserByid(1);
    System.out.println(user1);
    System.out.println(user==user1);
    sqlSession1.close();
}

只用cache时(二级缓存)必须加序列化

<cache/>

实体类

package com.hou.pojo;

import lombok.Data;
import java.io.Serializable;

@Data
public class User implements Serializable {
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}

小结:

  • 只有开启了二级缓存,在Mapper下有效
  • 所有数据都会先放在一级缓存
  • 只有当回话提交,或者关闭的时候,才会提交到二级缓存

3. 自定义缓存-ehcache

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.0</version>
</dependency>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
       diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home – 用户主目录
       user.dir  – 用户当前工作目录
       java.io.tmpdir – 默认临时文件路径
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

SpringBoot集成Mybaits

1、导入依赖

<!--引入mybatis依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

2、创建mapper.xml文件(用来编写SQL)

创建src/resources/mybatis/mapper/mapper.xml文件

<?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">

<!-- namespace:  绑定一个对应的  DAO/mapper接口 -->
<mapper namespace="com.zxm.springbootzxm.mapper.CheckMapper">

    <insert id="insert">
   insert into checkinfo (deposit, checkinTime, days, CustomerId, Roomid, remarks)
   values (#{deposit},#{checkInTime},#{days},#{customerId},#{roomId},#{remarks});
    </insert>

</mapper>

3、在springboot全局配置文件中指定mybatis的配置文件

mybatis:
#  configuration:(当指定mybatis的核心配置文件后,则不能使用 configuration属性 ,两者选其一)
#    #  配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
#    map-underscore-to-camel-case: true
#    # 打印sql,但是不出现在log中
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

#  指定mybatis核心配置文件,没有必要指定
#  config-location: classpath:mybatis/mybatis-config.xml
#  指定实体类对应的mapper.xml.文件
  mapper-locations: classpath:mybatis/mapper/*.xml
#  扫描实体类的包,默认别名就为这个类的类名
  type-aliases-package: com.zxm.springbootzxm.pojo
     map-underscore-to-camel-case: true
  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

注意:在springboot集成mybaits中mybatis的全局配置文件可不用创建,直接在application.yml中进行mybatis的配置即可

其他的难点

Mybatis中javaType和jdbcType对应关系

<resultMap type="java.util.Map" id="resultjcm">
  <result property="FLD_NUMBER" column="FLD_NUMBER" javaType="double" jdbcType="NUMERIC"/>
  <result property="FLD_VARCHAR" column="FLD_VARCHAR" javaType="string" jdbcType="VARCHAR"/>
  <result property="FLD_DATE" column="FLD_DATE" javaType="java.sql.Date" jdbcType="DATE"/>
  <result property="FLD_INTEGER" column="FLD_INTEGER"  javaType="int" jdbcType="INTEGER"/>
  <result property="FLD_DOUBLE" column="FLD_DOUBLE"  javaType="double" jdbcType="DOUBLE"/>
  <result property="FLD_LONG" column="FLD_LONG"  javaType="long" jdbcType="INTEGER"/>
  <result property="FLD_CHAR" column="FLD_CHAR"  javaType="string" jdbcType="CHAR"/>
  <result property="FLD_BLOB" column="FLD_BLOB"  javaType="Blob" jdbcType="BLOB" />
  <result property="FLD_CLOB" column="FLD_CLOB"  javaType="string" jdbcType="CLOB"/>
  <result property="FLD_FLOAT" column="FLD_FLOAT"  javaType="float" jdbcType="FLOAT"/>
  <result property="FLD_TIMESTAMP" column="FLD_TIMESTAMP"  javaType="java.sql.Timestamp" jdbcType="TIMESTAMP"/>
 </resultMap>
 
	JDBCType            JavaType
    CHAR                String
    VARCHAR             String
    LONGVARCHAR         String
    NUMERIC             java.math.BigDecimal
    DECIMAL             java.math.BigDecimal
    BIT                 boolean
    BOOLEAN             boolean
    TINYINT             byte
    SMALLINT            short
    INTEGER             int
    BIGINT              long
    REAL                float
    FLOAT               double
    DOUBLE              double
    BINARY              byte[]
    VARBINARY           byte[]
    LONGVARBINARY       byte[]
    DATE                java.sql.Date
    TIME                java.sql.Time
    TIMESTAMP           java.sql.Timestamp
    CLOB                Clob
    BLOB                Blob
    ARRAY               Array
    DISTINCT            mapping of underlying type
    STRUCT              Struct
    REF                 Ref
    DATALINK            java.net.URL[color=red][/color]

#{ }和${ }

#{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换.#{}可以有效防止sql注入。#{}可以接受简单类型或者pojo属性值。如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

${}表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。${}也可以接收pojo数据,可以使用OGNL解析出pojo的属性值.缺点:不能防止sql注入。

parameterType和resultType

parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。

resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis是一种持久层框架,它可以将SQL语句和Java代码分离,使得数据库操作更加简单、易于维护。下面是MyBatis基本使用: 1. 配置文件:MyBatis的配置文件包含数据库的连接信息、映射文件的位置等信息,需要在应用程序启动时加载。 2. 映射文件:MyBatis的映射文件包含SQL语句和Java对象之间的映射关系,需要在配置文件中指定映射文件的位置。 3. 数据库操作:MyBatis提供了多种方式进行数据库操作,如使用接口和注解等方式。 4. 会话工厂:MyBatis的会话工厂用于创建会话对象,会话对象可以用于执行SQL语句和管理事务等操作。 5. 事务管理:MyBatis的事务管理可以通过配置文件或编程方式进行管理,可以实现自动提交或手动提交事务。 下面是MyBatis基本使用步骤: 1. 编写配置文件,配置数据库连接信息和映射文件位置等信息。 2. 编写映射文件,实现SQL语句和Java对象之间的映射关系。 3. 创建会话工厂对象,通过配置文件构建会话工厂。 4. 创建会话对象,通过会话工厂获取会话对象。 5. 执行SQL语句,通过会话对象执行SQL语句,获取结果。 6. 提交事务,提交执行的SQL语句所在的事务。 7. 关闭会话对象和会话工厂,释放资源。 以上就是MyBatis基本使用步骤,需要注意的是,在使用MyBatis时,需要了解SQL语句的编写和Java对象的映射关系,才能更好地使用MyBatis进行数据库操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值