Mybatis学习笔记

一.第一个Mybatis程序

1.搭建环境

1.1搭建数据库:

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

1.2新建项目:

1.普通maven项目(检查maven配置)
2.删除其src文件夹,当作父工程
3.导入maven依赖mysql,mybatis,junit

2.创建子模块

2.1编写mybatis的核心配置文件

在src/main/resources下新建文件存放
每个!!Mapper.xml都需要在Mybatis核心文件中注册

<!--configuration核心配置文件-->
<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://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
2.2编写mybatis工具类

在src/main/java新建文件存放

//sqlSessionFactory --> sqlSession
public class MyBatisUtils {
  public static   SqlSessionFactory sqlSessionFactory;
    static {
        InputStream inputStream= null;
       
        try {
            //使用Mybatis第一步:获得sqlSessionFactory对象
            String resource="mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //有了SqlSessionFactory,可以从中获得SqlSession实例
    //SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

3.编写代码

3.1实体类:

属性,无参构造,有参构造,get和set,string

package com.wang.pojo;
//实体类
public class User {
    private int id;
    private  String name;
    private  String pwd;

    public User() {
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

3.2DAO接口:
package com.wang.dao;

import com.wang.pojo.User;

import java.util.List;

public interface UserDao {
    List<User> getUserList();
}

3.3接口实现类由原来的UserDaoImpl变成一个Mapper配置文件:
<?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.wang.dao.UserDao">

    <!--id方法名-->
    <select id="getUserList" resultType="com.wang.pojo.User">
        select * from  mybatis.user
    </select>

</mapper>

4.测试 Junit

4.1测试代码:
 @Test
    public void test(){
        //第一步:获得sqlSession对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //方式一:getMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
4.2经典报错及处理方法:
  • 报错一:

org.apache.ibatis.binding.BindingException: Type interface
com.wang.dao.UserMapper is not known to the MapperRegistry.

每一个Mapper.xml都需要在Mybatis核心文件中注册

<!--每一个Mapper.xml都需要在Mybatis核心文件中注册!!!-->
    <mappers>
        <mapper resource="com/wang/dao/UserMapper.xml"/>
    </mappers>
  • 报错二:

Caused by: java.io.IOException: Could not find resource com/wang/dao/UserMapper.xml

在build中配置resources,来防止资源导出失败的问题
在父子工程的pom.xml中都放入一份比较保险

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

步骤
导入包
配置数据库
建造工具类

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 关闭的标准模式

二. 增删改查(注意增删改需要提交事务)

1. namespace
namespace中的包名要和接口一致

2. select
id:就是对应的namespace的方法名
resultType:sql语句的返回值!
parameterType: 参数类型!

1.增删改查步骤:

1.1编写接口
public interface UserMapper {
    //查询全部用户
    List<User> getUserList();
    //通过id查询用户
    User getUserById(int id);
    //新增用户
    void insertUser(User user);
    //删除用户
    int deleteUser(int id);
    //修改用户
    int updateUser(User user);
}

1.2编写对应的mapper中的对应语句
<?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.wang.dao.UserMapper">

    <!--select 查询-->
    <select id="getUserList" resultType="com.wang.pojo.User">
        select * from  mybatis.user
    </select>
    <select id="getUserById" resultType="com.wang.pojo.User" parameterType="int">
        select * from  mybatis.user where id=#{id}
    </select>

    <!--insert 增加-->
    <insert id="insertUser" parameterType="com.wang.pojo.User">
        insert into mybatis.user(id, name, pwd) value(#{id},#{name},#{pwd})
    </insert>
    <!--delete 删除-->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>
    <!--update 修改-->
    <update id="updateUser" parameterType="com.wang.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>

</mapper>
1.3测试
@Test
    public void testgetUserById(){
    SqlSession session = MyBatisUtils.getSqlSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    System.out.println( mapper.getUserById(1));
    session.close();
}
@Test
    public void testInsertUser(){
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.insertUser(new User(4,"haha","777777"));
    sqlSession.commit();
    sqlSession.close();
}
@Test
    public void testDeleteUser(){
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.deleteUser(3);
    sqlSession.commit();
    sqlSession.close();
}

2.Map和模糊查询

2.1Map的用法
<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();
}
  • Map传递参数,直接在sql中取出key即可 parameterType=“map”
  • 对象传递参数,直接在sql中取出对象的属性即可 parameterType=“Object”
  • 只有一个基本参数类型的情况下,可以直接在sql中取到
  • 多个参数用Map或者注解
2.2 模糊查询
2.2.1.JAVA代码执行时,传递通配符% %
@Test
    List<User> list = mapper.getUserLike("%wang%")
2.2.2.在sql拼接处,使用通配符% %
<select id="getUserLike" resultType="com.hou.pogo.User">
    select * from mybatis.user where name like {%wang%}
</select>

三.配置解析

3.1.核心配置文件

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

3.2. 环境配置(environments)

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

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

  • Mybatis 默认的事务管理器是JDBC(还有一个事务管理器MANAGED),数据源共三种(pooled,unpooled,juni),默认连接池:POOLED
    池:用完可以回收。

3.3属性

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

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

3.3.1编写一个配置文件
driver = com.mysql.jdbc.Driver
url = "jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"
username = root 
password = 123456
3.3.2在核心配置文件中引入外部配置文件

注意顺序:
在这里插入图片描述

我的错误:

报错:在这里插入图片描述
原因:

配置文件里url的引号要去掉!!不然会把引号算作数据库url的内容
driver = com.mysql.jdbc.Driver
url= jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username = root
password = 123456

在核心配置文件中引入

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

<configuration>
    <!--引入外部配置文件-->
      <properties resource="db.properties">
        <property name="username" value="root"></property>
        <property name="password" value="1223456"></property>
    </properties>


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

    <!--每一个Mapper.xml都需要在Mybatis核心文件中注册!!!-->
    <mappers>
        <mapper resource="com/wang/dao/UserMapper.xml"/>
    </mappers>
</configuration>
总结:
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有统一字段,优先使用外部配置文件的!!

3.4.类型别名(typeAliases)

3.4.1类型别名可为 Java 类型设置一个缩写名字
<!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.wang.pojo.User" alias="User" />
    </typeAliases>
3.4.1扫描实体类的包,默认别名就为这个类的类名首字母小写(user)
<typeAliases>
        <package name="com.wang.pojo"/>
    </typeAliases>
使用情景和区别:
  • 在实体类,比较少的时候使用第一种,实体类多使用第二种。

  • 第一种可以自定义,第二则不行,但是 如果非要改,需要在实体类增加注解,则别名为其注解值 (hello)

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

3.5.设置

|设置名| 描述 |有效值| 默认值
|–|--|

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

3.6. 其他

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
  • mybatis-generator-core
  • mybatis-plus
  • 通用mapper

3.7. 映射器

3.7.1方式一: [推荐使用]mapper resource

使用相对于类路径的资源引用

<mappers>
    <mapper resource="com/wang/dao/UserMapper.xml"/>
</mappers>
3.7.2方式二:mapper class

使用映射器接口实现类的完全限定类名

<mappers>
    <mapper class="com.wang.dao.UserMapper" />
</mappers>

接口和它的Mapper必须同名
接口和他的Mapper必须在同一包下

3.7.3方式三:package name

将包内的映射器接口实现全部注册为映射器

<mappers>
    <package name="com.wang.dao" />
</mappers>

接口和它的Mapper必须同名
接口和他的Mapper必须在同一包下

3.8.生命周期和作用域(并发问题)

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

3.8.1 SqlSessionFactoryBuilder:
  • 一旦创建了 SqlSessionFactory,就不再需要它了 。
  • 局部变量
3.8.2 SqlSessionFactory:
  • 就是数据库连接池。
  • 一旦被创建就应该在应用的运行期间一直存在 ,没有任何理由丢弃它或-重新创建另一个实例 。 多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域。
  • 最简单的就是使用单例模式或者静态单例模式。
3.8.3 SqlSession:
  • 每个线程都应该有它自己的 SqlSession 实例。
  • 连接到连接池的请求!
  • SqlSession 的实例不是线程安全的,因此是不能被共享的 ,所以它的最佳的作用域是请求或方法作用域。
  • 用完之后赶紧关闭,否则资源被占用。

在这里插入图片描述

  • 这里的每一个Mapper就代表一个具体的业务

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

数据库中的字段

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

  • User(psaaword和pwd不一致)
public class User {

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

4.2 出现问题:

查询结果:
在这里插入图片描述

原因:

    <!--select 查询-->
    <select id="getUserById" resultType="user" parameterType="int">
    select * from  mybatis.user where id=#{id}
    //类型处理器
    //等效于 select id,name,pwd from  mybatis.user where id=#{id} 
</select>

4.3解决方案

核心配置文件

4.3.1起别名
<select id="getUserById" resultType="User"
    parameterType="int">
        select id,name,pwd as password from mybatis.user where id = #{id}
</select>
4.3.2resultMap 结果集映射
<?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.wang.dao.UserMapper">

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

    <!--select 查询-->
    <select id="getUserById" resultMap="UserMap" parameterType="int">
    select * from  mybatis.user where id=#{id}
    <!--等效于 select id,name,pwd from  mybatis.user where id=#{id} -->
</select>
  • 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 标志日志输出
5.1.1标准日志工厂的实现:在mybatis-confi中
<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

5.2 Log4j

5.2.1什么是Log4j
  • 控制日志信息输送的目的地是控制台、文件、GUI组件
  • 也可以控制每一条日志的输出格式;
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
5.2.2使用步骤

1.先导入Log4j的包
pom.xml下

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.在类路径下新建log4j.properties文件

### set log levels ###
log4j.rootLogger = DEBUG,console,file

### 输出到控制台 ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%c]-%m%n

### 输出到日志文件 ###
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/hou.log
log4j.appender.file.MaxFileSize=10mb 
log4j.appender.file.Threshold=DEBUG 
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

# 日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3.配置实现

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

4.Log4j使用

package com.wang.dao;

import com.wang.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 testgetUserById(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        logger.info("测试");
        System.out.println( mapper.getUserById(1));
        session.close();
    }
    @Test
    public void testLog4j(){
        logger.info("info:进入了testlog4j");
        logger.debug("debug:进入了testlog4j");
        logger.error("error:进入了testlog4j");
    }
}

六.分页

6.1使用Limit实现分页

语法:

//SELECT * from user limit startIndex,pageSize;
SELECT * from user limit 0,2;

xml

<!--分页-->
    <select id="getUserByLimit"  parameterType="map" resultType="User">
        select * from mybatis.user limit #{startIndex},#{endIndex}
    </select>

test

@Test
    public  void testLimit(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("endIndex",2);

        List<User> userList=mapper.getUserByLimit(map);
        for(User user:userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

6.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.wang.dao.UserMapper.getUserByRowBounds",
         null,rowBounds);

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

    sqlSession.close();
}

6.3 分页插件

pageHelper

七. 使用注解开发

在这里插入图片描述

在这里插入图片描述

7.1操作流程(注意绑定接口)

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>

本质:反射机制
底层:动态代理!

7.2Mybatis详细执行流程

Mybatis详细执行流程:

  1. Resource获取全局配置文件

  2. 实例化SqlsessionFactoryBuilder

  3. 解析配置文件流XMLCondigBuilder

  4. Configration所有的配置信息

  5. SqlSessionFactory实例化

  6. trasactional事务管理

  7. 创建executor执行器

  8. 创建SqlSession

  9. 实现CRUD

  10. 查看是否执行成功

  11. 提交事务

  12. 关闭

7.3 注解CRUD

7.3.1关于@parameter()注解:
  • 基本类型得参数或String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型可以不加,最好加
  • 在SQL中引用的就是我的@parameter()中设定的属性名!!
7.3.2代码实现
package com.wang.dao;

import com.wang.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);

}

MybatisUtils

package com.wang.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.wang.dao;

import com.wang.pojo.User;
import com.wang.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();
        }
    }
}

八. Lombok

在IDEA中安装lombok插件

配置

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>

常见注解

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@Data: 无参构造,get,set,toString,hashCode

在实体类上加注解

package com.hou.pojo;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

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

}

九. 多对一

9.1.建表

学生的tid和老师的id连起来(通过外键)

//一个老师
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, 'wang');
//多个学生
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);

9.2新建实体类/Mapper接口、 建立Mapper.xml,并测试是否能够成功

package com.wang.pojo;

import lombok.Data;

@Data
public class Teacher {
    private  int id;
    private  String name;
}
package com.wang.pojo;

import lombok.Data;

@Data
public class Student {
    private  int id;
    private  String name;
    //学生需要关联一个老师!!! private  int tid;不对
    private  Teacher teacher;

}

9.3按照查询嵌套处理

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.wang.dao.StudentMapper">
    <select id="getStudent" resultMap="StudentTeacher">
      select * from student;
    </select>

    <resultMap id="StudentTeacher" type="com.wang.pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--对象使用association-->
        <!--集合用collection-->
        <association property="teacher" column="tid"
                     javaType="com.wang.pojo.Teacher"
                     select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="com.wang.pojo.Teacher">
      select * from teacher where id = #{id};
    </select>

</mapper>

9.4按照结果嵌套处理

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>

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;
}

10.2. 按照结果查询

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

10.3. 按照查询嵌套处理

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

<resultMap id="TeacherStudent2" type="com.hou.pojo.Teacher">
    <collection property="studentList" column="id" javaType="ArrayList"
                ofType="com.hou.pojo.Student"
                select="getStudentByTeacherId"></collection>
</resultMap>

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

10.4小结

  • 关联 - association 多对一

  • 集合 - collection 一对多

  • javaType & ofType

JavaType 用来指定实体中属性类型
ofType 映射到list中的类型,泛型中的约束类型

- 注意点:

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

十一. 动态sql

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

11.1. 搭建环境

create table `blog`(
	`id` varchar(50) not null comment '博客id',
    `title` varchar(100) not null comment '博客标题',
    `author` varchar(30) not null comment '博客作者',
    `create_time` datetime not null comment '创建时间',
    `views` int(30) not null comment '浏览量'
	)ENGINE=InnoDB DEFAULT CHARSET=utf8

实体类

import lombok.Data;

import java.util.Date;

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

核心配置

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings

Mapper.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.wang.mapper.BlogMapper">
    <insert id="addBlog" parameterType="Blog">
        insert into mybatis.blog (id, title, author, create_time, views) values
        (#{id}, #{title}, #{author}, #{create_time}, #{views});
    </insert>
</mapper>

新建随机生成ID包

import org.junit.Test;

import java.util.UUID;

@SuppressWarnings("all")
public class IDUtiles {

    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    @Test
    public void  test(){
        System.out.println(getId());
    }

}

测试类:添加数据

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Date;
    public class MyTest {
    @Test
    public void addBlog(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setAuthor("houdongun");
        blog.setCreateTime(new Date());
        blog.setViews(999);
        blog.setTitle("first");

        blogMapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("second");
        blogMapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("third");
        blogMapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("forth");
        blogMapper.addBlog(blog);

        sqlSession.close();
    }
}
}

11.2. if

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

测试:

@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);
    }

    

11.3. choose、when、otherwise

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

11.4. trim、where、set

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

trim 可以自定义

SQL片段

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

  • 使用sql便签抽取公共部分

  • 在使用的地方使用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标签

11. 5. for-each

<!--ids是传的,#{id}是遍历的-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="and ("
                 close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

测试:

@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. 一级缓存

  • 开启日志
  • 测试一个session中查询两次相同记录。

缓存失效:

映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。 查询不同的mapper.xml 手动清除缓存
一级缓存默认开启,只在一次sqlseesion中有效

12.2. 二级缓存

开启全局缓存

<setting name="cacheEnabled" value="true"/>
在当前mapper.xml中使用二级缓存
<cache eviction="FIFO"
       flushInterval="60000"
       size="512"
       readOnly="true"/>

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下有效
所有数据都会先放在一级缓存
只有当回话提交,或者关闭的时候,才会提交到二级缓存

12.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>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值