MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 避免除了几乎所有的 JDBC 代码以及设置参数和获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录
持久化:将程序的数据在持久状态和瞬时状态转化的过程
持久层:完成持久化工作的代码块(将数据持久化)
内存有一个特性:断电即失,数据的运行都是在内存中运行的,如果不把数据持久化,一旦内存发生意外,数据就会丢失
持久化的方式有很多种,比如jdbc、io文件持久化 ...
层:界限明显
mybatis的实现有两种方式:
在mybatis中,所有操作只跟接口和配置文件相关
mybatis的获取,maven仓库:
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>
思路:搭建环境 > 导入mabatis > 编写代码 > 测试
create database `mybatis`;
use `mybatis`;
create table `user` (
	`id` int(20) not null,
	`name` varchar(30) default null,
	`password` varchar(30) default null,
	primary key(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into `user` values(1, ‘Lan‘, ‘123‘), (2, ‘Tian‘, ‘123‘), (3, ‘Jing‘, ‘123‘);
<dependencies>
    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
    </dependency>
</dependencies>
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>
package com.yue.pojo;
public class User {
    private int id;
    private String name;
    private String password;
    public User() {
    }
    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    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 getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", password=‘" + password + ‘\‘‘ +
                ‘}‘;
    }
}
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //先定义mybatis主配置文件的名称,从类路径的根开始(target/classes)
            String resource = "mybatis-config.xml";
            //读取这个配置文件
            InputStream in = Resources.getResourceAsStream(resource);
            //创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //创建SqlSessionFactory对象
            sqlSessionFactory =builder.build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() {
        //返回一个SqlSession对象
        return sqlSessionFactory.openSession();
    }
}
public interface UserMapper {
    List<User> getUserList();
}
<?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.yue.dao.UserDao">
    <select id="getUserList" resultType="com.yue.pojo.User">
        select * from user
    </select>
</mapper>
<?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核心配置文件-->
<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&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--注册mapper-->
    <mappers>
        <mapper resource="com/yue/dao/UserMapper.xml" />
    </mappers>
    
</configuration>
//第一种:getMapper 调用getMapper方法获取mapper对象UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> userList = mapper.getUserList();
//第二种:sqlSession.selectList(不推荐使用)List<User> userList = sqlSession.selectList("com.yue.dao.UserDao.getUserList");
@Testpublic void test() {    SqlSession sqlSession = MybatisUtils.getSqlSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);    List<User> userList = mapper.getUserList();    for (User user : userList) {        System.out.println(user);    }    sqlSession.close();}
查询操作:通过id查找用户信息
//根据id查询用户User getUserById(int id);
<select id="getUserById" resultType="com.yue.pojo.User" parameterType="int">    select * from user where id = #{id};</select>
@Testpublic void getUserById() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    User user = mapper.getUserById(1);    System.out.println(user);    sqlSession.close();}
标签属性
插入操作:添加一个新用户进入User表
注意:增删改需要提交事务
//插入一个用户int addUser(User user);
<insert id="addUser" parameterType="com.yue.pojo.User">    insert into user(id, name, password) values (#{id}, #{name}, #{password});</insert>
对于传进来的参数,对象中的属性,可以直接取出来
@Testpublic void addUser() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    mapper.addUser(new User(4, "Yue", "123"));    sqlSession.commit();    sqlSession.close();}
标签属性
更新操作:对User表中的某条记录进行更新
//修改用户int updateUser(User user);
<update id="updateUser" parameterType="com.yue.pojo.User">    update user set name = #{name}, password = #{password} where id = #{id};</update>
@Testpublic void updateUser() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    mapper.updateUser(new User(4, "Yin", "123"));    sqlSession.commit();    sqlSession.close();}
删除操作:删除User表中的某条记录
//删除一个用户int deleteUser(int id);
<delete id="deleteUser" parameterType="int">    delete from user where id = #{id};</delete>
@Testpublic void deleteUser() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    mapper.deleteUser(4);    sqlSession.commit();    sqlSession.close();}
模糊查询有两种方法:
例如:模糊查找名字
首先编写接口对应的方法
//模糊查询名字List<User> getUserLike();
在Java的执行时,传递通配符 %
<select id="getUserLike" resultType="com.yue.pojo.User">    select * from user where name like #{value}</select>
或者在SQL的拼接中,使用通配符
<select id="getUserLike" resultType="com.yue.pojo.User">    select * from user where name like "%"#{value}"%"</select>
测试:
@Testpublic void getUserLike() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    List<User> userList = mapper.getUserLike("%月%");    for (User user : userList) {        System.out.println(user);    }    sqlSession.close();}
使用Map传递参数的好处:不需要知道数据库中有什么字段,只需要查对应的字段
假设实体类中或者数据库中的表的字段或参数过多的时候,可以考虑使用map
//使用Map传递参数添加用户int addUser2(Map<String, Object> map);
<insert id="addUser2" parameterType="map">    insert into user(id, name, password) values(#{id}, #{name}, #{password});</insert>
@Testpublic void testAdd() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    HashMap<String, Object> map = new HashMap<>();    map.put("id", 5);    map.put("name", "Qin");    map.put("password", "123");    mapper.addUser2(map);    sqlSession.commit();    sqlSession.close();}
Mybatis的核心配置文件为:mybatis-config.xml
该配置文件包含了会深深影响Mybatis行为的设置和属性信息
作用:导入外部的配置文件
创建一个properties文件,在配置文件中,可以把其导入
db.properties:
driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMTusername=rootpassword=1234
在核心配置文件中配置:
<!--引入外部配置文件--><properties resource="db.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><mappers>    <mapper resource="com/yue/dao/UserMapper.xml"/></mappers>
在这个标签里面,还可以自己加一些属性:
<properties resource="db.properties">    <property name="username" value="" /></properties>
优先使用外部配置文件
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
| cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true | 
|---|---|---|---|
| lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType属性来覆盖该项的开关状态。 | true | false | false | 
| aggressiveLazyLoading | 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods)。 | true | false | false (在 3.4.1 及之前的版本中默认为 true) | 
| multipleResultSetsEnabled | 是否允许单个语句返回多结果集(需要数据库驱动支持)。 | true | false | true | 
| useColumnLabel | 使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。 | true | false | true | 
| useGeneratedKeys | 允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。 | true | false | False | 
| autoMappingBehavior | 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。 | NONE, PARTIAL, FULL | PARTIAL | 
| autoMappingUnknownColumnBehavior | 指定发现自动映射目标未知列(或未知属性类型)的行为。 NONE: 不做任何反应WARNING: 输出警告日志(‘org.apache.ibatis.session.AutoMappingUnknownColumnBehavior‘的日志等级必须设置为WARN)FAILING: 映射失败 (抛出SqlSessionException) | NONE, WARNING, FAILING | NONE | 
| defaultExecutorType | 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 | SIMPLE REUSE BATCH | SIMPLE | 
| defaultStatementTimeout | 设置超时时间,它决定数据库驱动等待数据库响应的秒数。 | 任意正整数 | 未设置 (null) | 
| defaultFetchSize | 为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。 | 任意正整数 | 未设置 (null) | 
| defaultResultSetType | 指定语句默认的滚动策略。(新增于 3.5.2) | FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT(等同于未设置) | 未设置 (null) | 
| safeRowBoundsEnabled | 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。 | true | false | False | 
| safeResultHandlerEnabled | 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。 | true | false | True | 
| mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 | true | false | False | 
| localCacheScope | MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。 | SESSION | STATEMENT | SESSION | 
| jdbcTypeForNull | 当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 | JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。 | OTHER | 
| lazyLoadTriggerMethods | 指定对象的哪些方法触发一次延迟加载。 | 用逗号分隔的方法列表。 | equals,clone,hashCode,toString | 
| defaultScriptingLanguage | 指定动态 SQL 生成使用的默认脚本语言。 | 一个类型别名或全限定类名。 | org.apache.ibatis.scripting.xmltags.XMLLanguageDriver | 
| defaultEnumTypeHandler | 指定 Enum 使用的默认 TypeHandler。(新增于 3.4.5) | 一个类型别名或全限定类名。 | org.apache.ibatis.type.EnumTypeHandler | 
| callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 | true | false | false | 
| returnInstanceForEmptyRow | 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) | true | false | false | 
| logPrefix | 指定 MyBatis 增加到日志名称的前缀。 | 任何字符串 | 未设置 | 
| logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 | 
| proxyFactory | 指定 Mybatis 创建可延迟加载对象所用到的代理工具。 | CGLIB | JAVASSIST | JAVASSIST (MyBatis 3.3 以上) | 
| vfsImpl | 指定 VFS 的实现 | 自定义 VFS 的实现的类全限定名,以逗号分隔。 | 未设置 | 
| useActualParamName | 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters选项。(新增于 3.4.1) | true | false | true | 
| configurationFactory | 指定一个提供 Configuration实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration()的方法。(新增于 3.2.3) | 一个类型别名或完全限定类名。 | 未设置 | 
typeAliases 的配置,需要写在 setting 之后
在映射文件中,对于返回类型,每次都需要写全限定名,如:
<insert id="addUser" parameterType="map">    insert into user(id, name, password) values(#{id}, #{name}, #{password});</insert>
类型别名typeAliases是为Java类型设置一个短的名字,它只和XML配置有关,存在的意义仅用来减少完全限定名的冗余。例如:
<typeAliases>  <typeAlias alias="Author" type="domain.blog.Author"/>  <typeAlias alias="Blog" type="domain.blog.Blog"/>  <typeAlias alias="Comment" type="domain.blog.Comment"/>  <typeAlias alias="Post" type="domain.blog.Post"/>  <typeAlias alias="Section" type="domain.blog.Section"/>  <typeAlias alias="Tag" type="domain.blog.Tag"/></typeAliases>
当这样配置时,Author 可以用在任何使用 domain.blog.Author 的地方
除了指定单个类之外,还可以指定一个包名,MyBatis会在包名下搜索需要的JavaBean,比如:
<typeAliases>	<package name="domain.blog"/></typeAliases>
每一个在包 domain.blog 中的Bean,在没有注解的清空下,会使用Bean的首字母小写的非限定类名来作为它的别名
比如domain.blog.Author 的别名为:author
如果使用注解的话,是在POJO上方使用注解
@Alias("author")public class Author {    ...}
这种写法,还需要指定包名配置
使用了别名之后的映射文件:
<select id="getUserList" resultType="user">    select * from user</select>
MyBatis中有一些默认的别名,基本类型的别名为在前面加下划线,如int的别名为_int,如果不加下划线,则实际类型会变为包装类
MapperRegistry:注册绑定我们的Mapper文件
方式一:
<mappers>    <mapper resource="com/yue/dao/UserMapper.xml"/></mappers>
方式二:使用class文件绑定注册
<mappers>    <mapper class="com.yue.dao.UserMapper.xml"/></mappers>
注意点:
方式三:使用扫描包进行注入绑定
<mappers>    <package name="com.yue.dao" /></mappers>
注意点:
如果一个数据库操作出现了异常,我们需要排错,日志就是最好的助手
曾经:为了调试程序,我们使用Sout语句或者debug功能
现在:日志工厂
| 设置名 | 描述 | 
|---|---|
| logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找 | 
有效值:
在Mybatis中具体使用哪个日志实现,在核心配置文件中设定
<settings>    <setting name="logImpl" value="STDOUT_LOGGING"/></settings>
我们一般都设置使用LOG4J日志,通过LOG4J,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件等等
步骤:
<dependency>    <groupId>log4j</groupId>    <artifactId>log4j</artifactId>    <version>1.2.17</version></dependency>
#将等级为DEBUG的日志信息输出到console和file这两个目的地log4j.rootLogger=debug,console,file#consolelog4j.appender.console = org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target = System.outlog4j.appender.console.Threshold = DEBUGlog4j.appender.console.layout = org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern = [%c]-%m%nlog4j.appender.file = org.apache.log4j.RollingFileAppenderlog4j.appender.file.File = ./log/yue.loglog4j.appender.file.MaxFileSize = 10mblog4j.appender.file.Threshold=DEBUGlog4j.appender.file.layout = org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern = [%p][%d{yy-MM-dd}][%c]%m%n#日志输出级别log4j.logger.org.mybatis = DEBUGlog4j.logger.java.sql = DEBUGlog4j.logger.java.sql.Statement = DEBUGlog4j.logger.java.sql.ResultSet = DEBUGlog4j.logger.java.sql.PreparedStatement = DEBUG
<settings>    <setting name="logImpl" value="LOG4J"/></settings>
ResultMap:结果集映射
解决的问题:属性名与字段名不一致
说明
假如现在有一个User实体类,数据库中表定义的字段属性名为psw,而实体类中定义的属性名为password
在利用xml配置进行查询之后,出现:
User{id=1, name=‘月光‘, password=‘null‘}
SQL的完整语句为:
select id,name,pwd from user where id = #{id}
解决方法
<select id="getUserById" resultType="com.yue.pojo.User" parameterType="int">    select id, name, psw as password from user where id = #{id};</select>
<resultMap id="UserMap" type="user">    <!--		column:数据库中的字段		property:实体类中的属性	-->        <!--<result column="id" property="id" />-->    <!--<result column="name" property="name" />-->    <result column="psw" property="password" /></resultMap><select id="getUserById" resultMap="UserMap" parameterType="int">    select * from user where id = #{id};</select>
对于resultMap中不需要映射的属(一样的字段),可以不填写
目的:减少数据的处理量
使用 Limit 实现分页
SQL语法:
SELECT * FROM user LIMIT startIndex, pageSize;
例如:每页显示两个
SELECT * FROM user LIMIT 0, 2;
如果只传入一个参数n,则返回 [0,n)的数据
实现:
//分页查询List<User> getUserByLimit(Map<String, Integer> map);
<resultMap id="UserMap" type="user">    <result column="psw" property="password" /></resultMap><select id="getUserByLimit" parameterType="map" resultMap="UserMap">    select * from user limit #{startIndex}, #{pageSize}</select>
@Testpublic void getUserByLimit() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    HashMap<String, Integer> map = new HashMap<>();    map.put("startIndex", 0);    map.put("pageSize", 2);    List<User> userByLimit = mapper.getUserByLimit(map);    for (User user : userByLimit) {        System.out.println(user);    }    sqlSession.close();}
还可以使用RowBounds实现分页,通过Java代码层面实现分页
也可以通过第三方插件实现(例如:PageHelper)
使用注解的步骤:
public static SqlSession getSqlSession() {    //设置参数为true,自动提交事务    return sqlSessionFactory.openSession(true);}
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, psw) values (#{id}, #{name}, #{password})")    int addUser(User user);    @Update("update user set name=#{name}, psw=#{password} where id = #{id}")    int updateUser(User user);    @Delete("delete from user where id = #{id}")    int deleteUser(@Param("id") int id);}
<!--绑定接口--><mappers>    <mapper class="com.yue.dao.UserMapper" /></mappers>
@Testpublic void test() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    UserMapper mapper = sqlSession.getMapper(UserMapper.class);    List<User> users = mapper.getUsers();    for (User user : users) {    	System.out.println(user);    }    User userByID = mapper.getUserByID(1);    System.out.println(userByID);    mapper.addUser(new User(5, "天", "123"));    mapper.updateUser(new User(5, "地", "123"));        mapper.deleteUser(5);    sqlSession.close();}
@Param()注解
CREATE TABLE `teacher` (	`id` INT(10) NOT NULL,	`name` VARCHAR(30) DEFAULT NULL,	PRIMARY KEY(`id`)) ENGINE=INNODB DEFAULT CHARSET=utf8;insert into teacher(id, name) values(1, "龙傲天");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, ‘小一‘, 1);insert into student (id, name, tid) values (2, ‘小二‘, 1);insert into student (id, name, tid) values (3, ‘小三‘, 1);insert into student (id, name, tid) values (4, ‘小四‘, 1);insert into student (id, name, tid) values (5, ‘小五‘, 1);
导入lombok
新建实体类Teacher、Student
创建两个对应的mapper:StudentMapper、TeacherMapper
创建两个对应的xml文件
在核心配置中绑定注册Mapper接口
处理多对一关系有两种方式:
现在想要查询所有的学生信息,以及对应的老师信息
实体类为:
@Datapublic class Student {    private int id;    private String name;    //学生需要关联一个老师    private Teacher teacher;}@Datapublic class Teacher {    private int id;    private String name;}
SQL语句为:
select s.id, s.name, t.namefrom student s, teacher twhere s.tid = t.id;
接口为:
public interface StudentMapper {    List<Student> getStudent();}
接着编写配置文件
查询所有的学生信息,以及对应的老师信息
<select id="getStudent" resultMap="Student">    select * from student;</select>
这样查询到的结果中,所有的teacher为null
思路:
<!--查询所有学生信息--><select id="getStudent" resultMap="StudentTeacher">    select * from student;</select><resultMap id="StudentTeacher" type="Student">    <result property="id" column="id" />    <result property="name" column="name" />    <!--		第三个属性为:Teacher		复杂的属性,需要单独处理		对象:使用association        集合:使用collection	-->    <association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/></resultMap><select id="getTeacher" resultType="Teacher">    select * from teacher where id = #{id}</select>
<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="Student">    <result property="id" column="sid" />    <result property="name" column="sname" />        <association property="teacher" javaType="Teacher">        <result property="name" column="tname" />    </association></resultMap>
Mysql中多对一查询方式:
例如:一个老师对应多个学生(对于老师而言,就是一对多关系)
@Datapublic class Teacher {    private int id;    private String name;    //一个老师拥有多个学生    private List<Student> students;} @Datapublic class Student {    private int id;    private String name;    private int tid;}
Teacher getTeacher2(@Param("tid") int id);
<select id="getTeacher2" resultMap="TeacherStudent2">    select * from teacher where id = #{tid}</select><resultMap id="TeacherStudent2" type="Teacher">    <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherID" /></resultMap><select id="getStudentByTeacherID" resultType="Student">    select * from student where tid = #{tid}</select>
接口
//获取指定老师下的所有学生及老师的信息Teacher getTeacher(@Param("tid") int id);
Mapper.xml
<select id="getTeacher" resultMap="TeacherStudent">    select s.id sid, s.name sname, t.name tname, t.id tid    from student s, teacher t    where s.tid = t.id and t.id = #{tid}</select><resultMap id="TeacherStudent" type="Teacher">    <result property="id" column="tid" />    <result property="name" column="tname" />    <collection property="students" ofType="Student" >        <result property="id" column="sid" />        <result property="name" column="sname" />        <result property="tid" column="tid" />    </collection></resultMap>
测试
@Testpublic void test() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);    Teacher teacher = mapper.getTeacher(1);    System.out.println(teacher);    sqlSession.close();}
使用步骤:
常用注解:
@Data:无参构造、get、set、tostring、hashcode、equals@AllArgsConstructor:有参构造@NoArgsConstructor:无参构造
动态SQL:根据不同的条件生成不同的SQL语句
动态SQL元素和JSTL或基于类似XML的文本处理器相似
常用标签:
数据库创建
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;
编写实体类
@Datapublic class Blog {    private String id;    private String title;    private String author;    private Date createTime;    private int views;}
在这里面,createTime的命名与数据库中的不一致,为了保持一致,在
<settings>    <setting name="mapUnderscoreToCamelCase" value="true"/></settings>
插入数据
insert into blog value("1", "Java", "蓝天", now(), 9999),("2", "MyBatis", "蓝天", now(), 1000),("3", "Spring", "蓝天", now(), 9999),("4", "SpringBoot", "蓝天", now(), 9999),("5", "SpringMVC", "蓝天", now(), 9999);
public interface BlogMapper {    //查询博客    List<Blog> queryBlogIF(Map map);}
mapper编写
<select id="queryBlogIF" parameterType="map" resultType="blog">    select * from blog where 1 = 1    <if test="title != null">        and title = #{title}    </if>    <if test="author">        and author = #{author}    </if></select>
@Testpublic void test1() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);    HashMap map = new HashMap();    map.put("title", "Java");    List<Blog> blogs = mapper.queryBlogIF(map);    for (Blog blog : blogs) {        System.out.println(blog);    }    sqlSession.close();}
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
还是上面的例子,但是策略变为:
<select id="queryBlogIF" resultType="Blog" resultType="blog">    SELECT * FROM BLOG WHERE    <where>        <choose>            <when test="title != null">                title = #{title}            </when>            <when test="author != null">                and author = #{author}            </when>            <otherwise>                AND views = #{views}            </otherwise>        </choose>    </where></select>
如果现在有个SQL:
<select id="queryBlogIF" resultType="Blog">    SELECT * FROM BLOG     WHERE    <if test="state != null">        state = #{state}    </if>    <if test="title != null">        AND title like #{title}    </if></select>
如果没有匹配条件的话,最终SQL会变成
SELECT * FROM BLOGWHERE
这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:
SELECT * FROM BLOGWHEREAND title like ‘someTitle’
MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。
而这,只需要一处简单的改动:
<select id="queryBlogIF" resultType="Blog">    SELECT * FROM BLOG    <where>        <if test="state != null">            state = #{state}        </if>        <if test="title != null">            AND title like #{title}        </if>    </where></select>
where元素只会在至少有一个子元素的条件返回SQL子句的情况下才去插入where子句
而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能
比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">  ...</trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)
上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容
用于动态更新语句的类似解决方案叫做 set
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:
<update id="updateBlog" parameterType="map">    update blog    <set>        <if test="title != null">            title = #{title},        </if>        <if test="author != null">            author = #{author},        </if>    </set>    where id = #{id}</update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
来看看与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=",">  ...</trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值
作用:把一些功能的部分抽取出来,方便复用
<sql id="if-title-author">    <if test="title != null">        title = #{title}    </if>    <if test="author">        and author = #{author}    </if></sql><select id="queryBlogIF" parameterType="map" resultType="blog">    select * from blog    <where>        <include refid="if-title-author"></include>    </where></select>
作用:对一个集合进行遍历,通常是在构建IN条件语句的时候
select * from blog where 1 = 1 and (id = 1 or id = 2 or id = 3)
<select id="queryBlogForeach" parameterType="map" resultType="blog">    select * from blog    <where>        <foreach collection="ids" item="id" open="and ("  close=")" separator="or">            id = #{id}        </foreach>    </where></select>
@Testpublic void test2() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);    HashMap map = new HashMap();    ArrayList<Integer> ids = new ArrayList<>();    ids.add(1);    ids.add(2);    ids.add(3);    map.put("ids", ids);    List<Blog> blogs = mapper.queryBlogForeach(map);    for (Blog blog : blogs) {        System.out.println(blog);    }    sqlSession.close();}
缓存:存在内存中的临时数据
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上查询,而是从缓存中查询,从而提高了效率,解决了 高并发系统的性能问题
使用缓存可以减少和数据库的交互次数,减少系统开销,提高系统效率
经常查询并且不经常改变的数据,可以使用缓存
MyBatis系统中默认定义了两级缓存:一级缓存、二级缓存
缓存失效的情况:
查询不同的东西
增删改操作,可能会改变原来的数据,所以必定会刷新缓存
查询不同的Mapper.xml
手动清理缓存:sqlSession.clearCache()
一级缓存默认开启,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
一级缓存相当于一个Map
在核心配置文件中开启
<cache/>
可以对其中一些属性进行定义,详细见官网文档
原文:https://www.cnblogs.com/lloco/p/14725837.html