Mybatis

mybatis – MyBatis 3 | 中文文档



  • 依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>


持久层

持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 数据库(jdbc),io文件持久化


持久层

Dao层,Service层,Controller层…

  • 完成持久化工作的代码块

  • 层界限十分明显。






常用注解

    //别名
@Alias("指定别名")

//SQL 注解
@Select(" SQL ")

//映射属性
@Param("映射的基本类型参数名称") 参数

//Lombok
@Data

//过滤警告
@SuppressWarnings("all")





配置

依赖

  • 依赖:mysql、mybatis、junit
<dependencies>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
</dependencies>


资源导出

  • 找不到mapper文件:maven中存在资源过滤,target包中没有mapper配置文件。

    解决方法:①拷贝mapper文件到target对应的软件包中

    ​ ②maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案;

<!--在pom.xml文件中配置resources,来防止我们资源导出失败的问题-->
<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>


核心配置文件

  • resources

    • *db.properties
    # ${ Value }
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=123456

    # ${ jdbc.Value }
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=123456

    • mybatis-confg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--核心配置文件-->

<!--引入外部配置文件-->
<properties resource="db.properties">
</properties>

<!--实体类起别名-->
<typeAliases>
</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>

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
<mappers>
</mappers>
</configuration>


Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 绑定一个对应的Dao/Mapper接口-->
<mapper namespace=" packName ">

<!--id对应接口中方法名称-->
<!--parameterType="":传递值-->
<!--resultType:返回结果-->

</mapper>





第一个Mybatis程序

创建子模块

  1. 配置文件 mybatis-config.xml

2.编写mybatis工具类(utils)

//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();
}
}

//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();//自动提交事务则参数加入 true
}
}

3.编写代码

  • 实体类pojo
public class User {
}

  • Dao层
public interface UserDao {
//方法名:getUserList
List<User>getUserList();
}

  • 接口实现类 – 由原来的UserDaoImpl类变成一个Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.chen.dao.UserDao">

<!--id对应方法名称:List<User>getUserList();-->
<!--resultType:返回结果-->
<select id="getUserList" resultType="com.chen.pojo.User">
select * from mybatisb.user
</select>

</mapper>
  • 测试类
@Test
public void test(){
//第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();

//执行SQL
UserDao userdao=sqlSession.getMapper(UserDao.class);
List<User> userList = userdao.getUserList();

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

//关闭SqlSession
sqlSession.close();
}





CRUD

  • Test
     //第一步:获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();

//执行SQL
UserMapper userdao=sqlSession.getMapper(UserMapper.class);

//代码

//关闭SqlSession
sqlSession.close();


  • namespace :接口位置

  • id :就是对应的namespace里面的方法名;

  • resultType :Sql语句执行的返回值;

  • parameterType:接收参数类型,(在接口中获取对应的值对数据库进行操作)(可省略:int)



1、namespace

namespace中的包名要和Dao/mapper接口的包名一致!

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

<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.chen.dao.UserMapper">
</mapper>


2、select

选择,查询语句:

  • UserMapper接口
//查询全部用户
List<User>getUserList();

//根据ID查询用户
User getUserById(int id);

  • UserMappe接口实现xml文件:
    • id 对应接口中的方法名称
<!--查询全部用户-->
<select id="getUserList" resultType="com.chen.pojo.User" >
select * from mybatisb.user
</select>

<!--根据ID查询用户-->
<select id="getUserById" parameterType="int" resultType="com.chen.pojo.User">
select * from mybatis.user where id = #{id}
</select>

  • Test
//查询全部
List<User> userList = userdao.getUserList();

//查询指定
User user = mapper.getUserById(1);


模糊查询

  • 接口
//模糊查询
List<User>getUserLike(String value);

  • 实现
	<!--模糊查询-->
<select id="getUserLike" resultType="com.chen.pojo.User">
select * from mybatisb.user where name like #{value}

<!-- ②在sql拼接中使用通配符 【推荐:防止sql注入】-->
select * from mybatisb.user where name like "%"#{value}"%"
</select>

  • Test
//模糊查询
//①传递通配符 %%
List<User> userList=mapper.getUserLike("%陈%");

//②在sql拼接中使用通配符【推荐】
List<User> userList=mapper.getUserLike("陈");


通配符

  • 模糊查询

    1、Java代码执行的时候,传递通配符 %%

    List<User> userList=mapper.getUserLike("%陈%");

    2、在sql拼接中使用通配符

    <select id="getUserLike" resultType="com.chen.pojo.User">
    select * from mybatisb.user where name like "%"#{value}"%"
    </select>


3、insert

  • 增删改需要提交事务:sqlSession.commit();

插入语句:

  • UserMapper接口
//insert用户
int addUser(User user);

  • UserMappe接口实现xml文件:
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.chen.pojo.User">
insert into mybatisb.user (id,name,pwd) values(#{id},#{name},#{pwd});
</insert>

  • Test
int res = mapper.addUser(new User(9,"chen","9999"));//返回数据影响值

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

  • usegeneratekeys:useGeneratedKeys 是 MyBatis 中的一个属性,通常用于配置在插入操作(INSERT)时是否返回生成的主键。



4、update

  • 增删改需要提交事务:sqlSession.commit();

更新语句:

  • UserMapper接口
//update用户
int updateUser(User user);

  • UserMappe接口实现xml文件:
<update id="updateUser" parameterType="com.chen.pojo.User">
update mybatisb.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>

  • Test
mapper.updateUser(new User(1, "cccccccc", "222222222"));

sqlSession.commit();


5、delete

  • 增删改需要提交事务:sqlSession.commit();

删除语句:

  • UserMapper接口
//delete用户
int deleteUser(int id);

  • UserMappe接口实现xml文件:
<delete id="deleteUser" parameterType="int">
delete from mybatisb.user where id=#{id}
</delete>

  • Test
mapper.deleteUser(9);

sqlSession.commit();

注意点

  • 增删改需要提交事务:sqlSession.commit();


5、万能Map

  • 假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Mp!

  • Map传递参数,直接在sql中取出key即可!【parameterType=”map”】对象传递参数,直接在sql中取对象的属性即可!【parameterType=”Object”】只有一个基本类型参数的情况下,可以直接在sq中取到!
    多个参数用Map,或者注解

  • 局部数据操作,不用操作数据表里面的全部数据(比如插入,可以为空的字段我不传值)

  • Map<String,Object>

    第一个类型(String)不用变,可理解为键的名称必定为String

    第二个类型(Object、String、Integer。。。),看需求传递的是纯单一类型的数据则选择该类型,对类型选择对象


  • 接口
//insert用户:万能Map
int addUser2(Map<String, Object> map);

//根据ID查询用户
User getUserById2(Map<String,Object> map);

  • Sql语句
<!--
传递map的key
-->
<insert id="addUser2" parameterType="map">
insert into mybatisb.user (id,pwd) values(#{userId},#{passWord});
</insert>

<select id="getUserById2" parameterType="map" resultType="com.chen.pojo.User">
select * from mybatisb.user where id = #{id} and name = #{name}
</select>
  • Test
    Map<String, Object> map = new HashMap<String, Object>();
map.put("userId",5);
map.put("password","99999222222");
mapper.addUser2(map);

HashMap<String, Object> map = new HashMap<>();
map.put("id",1);
User user= mapper.getUserById2(map);





配置解析

1、核心配置文件

  • mybatis-config.xml
<!--
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)

environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
-->


2、环境配置(environments)

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

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

  • default – 默认环境

    • 事务管理器:transactionManager

      • 默认的事务管理器(transactionManager)为JDBC
    • 数据源连接池(dataSource):POOLED

image-20230722151943037

  • Mybats 默认管理器是:JDBC,默认连接池:POOLED
<environments default="development"><!--default:默认环境-->

<environment id="development">
<transactionManager type="JDBC"/><!--事务管理器-->
<dataSource type="POOLED"><!--数据源-->
<property/>
</dataSource>
</environment>

<environment id="test">
</environment>

</environments>


3、属性优化(properties)

  • 我们可以通过properties属性实习引用配置文件

  • 1、编写配置文件(db.propertise)

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

  • 2、引入外部配置文件(mybatis-config.xml)

    • 获取外部文本的property属性
<configuration><!--核心配置文件-->

<!--引入外部配置文件,放在首位-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</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>

</configuration>

在核心配置文件中映入

 <!--如在外部文件中已经定义,则优先读取外部文件属性,第二优先--> 
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
  • 可以直接引入外部文件
  • 可以在其中直接一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的


4、类型别名优化(typeAliases)

  • mybatis-config.xml

  • 第一种:一个类起一个别名(实体类比较少推荐使用)

<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.chen.pojo.User" alias="User"/>
</typeAliases>
  • 第二种:指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean(实体类比较多推荐使用)
    • 扫描实体类的包。它的默认别名为这个类的别名,首字母小写
<typeAliases>
<package name="com.chen.pojo"/>
</typeAliases>
  • 想diy别名,使用注解指定别名:
@Alias("uu")

  • 使用
<select id="getUserList" resultType="user" >
select * from mybatisb.user
</select>


5、设置(settings)

image-20230529170548324

<settings>
<setting name="cacheEnabled" value="true"/><!--缓存-->
<setting name="lazyLoadingEnabled" value="true"/><!--懒加载 -->
<setting name="logImpl" value="STDOUT_LOGGING"/><!--标准的日志工厂实现-->
</settings>


6、其他

plugins 插件

  • mybatis-generator-core
  • mybatis-plus


7、映射器(mappers)

  • 每一个Mapper.xml都需要在Mybatis核心配置文件中注册
<mappers>
<mapper resource="com/chen/dao/UserMapper.xml"/>
<mapper class="com.chen.dao.UserMapper"/>
<package name="com.chen.dao"/>
</mappers>

方式一:resource (推荐使用)

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

方式二:使用class文件绑定注册

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="com.chen.dao.UserMapper"/>
</mappers>
  • 注意点
    • 接口和它的Mapper配置文件必须同名
    • 接口和它的Mapper配置文件必须在同一个包下

方式三:使用扫描包进行注入绑定

<package name="com.chen.dao"/>


8、生命周期和作用域

image-20230529172846031

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

SqlSessionFactory

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


SqlSessionFactory:

  • ·说白了就是可以想象为:数据库连接池
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • ·因此SqlSessionFactory的最佳作用域是应用作用域。
  • ·最简单的就是使用单例模式或者静态单例模式。


SqlSession

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

image-20230530113057839



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

  • 字段名

image-20230530114240271


  • public class User {
        private int id;
        private String name;
        private String password;
    }
    

    <br/>

    - Test

    ```java
    User{id=1, name='cccccccc', password='null'}

  • 类型处理器
select * from mybatisb.user where id = #{id}

select id,name,pwd from mybatisb.user where id = #{id}

解决方法

  • 起别名(字段名 as 属性名 (pwd as password))
<select id="getUserById" parameterType="int" resultType="User">
select id,name,pwd as password from mybatisb.user where id = #{id}
</select>

resultMap

结果集映射

  • 不一样的才需要映射,一样的可以不映射
//   表字段:id name pwd
// 属性名:id name password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段:列 property实体类中的属性-->
<!-- 字段和属性名一样不用映射,自动赋值
<result column="id" property="id"/>
<result column="name" property="name"/>
-->
<result column="pwd" property="password"/>
</resultMap>

<!--resultMap,找到resultMap标签对应的id-->
<select id="getUserById" resultMap="UserMap">
select * from mybatisb.user where id = #{id}
</select>





日志

标准日志工厂

如果一个数超库操作,出现了异常,我们需要排错。日志就是最好的助手
曾经:sout、debug
现在:日志工厂

image-20230530163319025

  • STDOUT_LOGGING
<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

image-20230530164746227



LOG4J(3.5.9 起废弃)

  • L0g4是APch的一个升派项日,通过使用L0g4,我们可以控制日志信息输送的目的地是控制台、文件、GU组件
  • 我们也可以控制每一条日志的输出格式
  • 过定义每一条日志信息的级别,我门能修更加细致地控制日志的生成过程
  • 通过一个配置文生来灵活地进行配骨,而不需要修改应用的代码

1、导包

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

2、log4j.properties

#将等级为DEBUG的日志信息输出到console和吁iLe这两个目的地,console和吁iLe的定义在下面的代码
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/chen.log
log4j.appender.file.MaxFilesize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
1og4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
1og4j.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、配置log4j为日志的实现

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

4、Log4j的使用

  • 在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
  • 日志对象,参数为当前类的class
  • static->提升作用域
static Logger logger= Logger.getLogger(UserDaoTest.class);
  • 日志级别
//日志文件信息的标记

logger.info("info:进入了testLog4j方法");//提示
logger.debug("info:进入了testLog4j方法");//debug
logger.error("info:进入了testLog4j方法");//请求错误





使用limit分页

SQL语法

  • 只有一个因数:则为lastIndex –> [0,lastIndex]

  • 起始(startIndex),一页显式的数量(pageSize)

select * from mybatisb.user limit x  //[0,x]

select * from mybatisb.user limit startIndex,pageSize

1、接口

//分页
List<User> getUserByLimit(Map<String,Integer> map);

2、Mapper.xml

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

<!--分页查询-->
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatisb.user limit #{startIndex},#{pageSize}
</select>


3、test

SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex",0);
map.put("pageSize",5);
List<User> userList=mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();





注解开发

结果集数据无法映射属性

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

1、注解在接口上实现

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

2、配置文件绑定接口

<!--绑定接口-->
<mappers>
<mapper class="com.chen.dao.UserMapper"></mapper>
</mappers>


CRUD

1.查询

  • 方法存在多个参数,所有的参数前面必须加上:**@Param(‘id’)** – SQL语句获取值的key
@Select("select * from user")
List<User> getUsers();

//方法存在多个基本类型参数,所有的参数前面必须加上:@Param('id')
@Select("select * from user where id=#{id} and name=#{namec}")
User getUserById(@Param("id") int id,@Param("namec") String name);

2.插入

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

3.更新

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

4.删除

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

关于@Param()注解

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





Lombok

使用:(自动生成get和set方法)

  • 使用注解后点击编译器左边的看结构

  • 导包

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.28</version>
    <scope>provided</scope>
    </dependency>

  • 在实体类上使用即可

    @Data
    @NoArgsConstructor //无参构造
    @AllArgsConstructor, //全参构造
    @Getter
    @Setter
    @ToString
    @RequiredArgsConstructor





多对一处理

  • mybatis-06

  • 多方:关联

  • 一方:集合

1.导入lombok导包

2.新建实体类Teacher,.Student

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


@Data
public class Student {
private int id;
private String name;
// 关联外键的类
private Teacher teacher;
}

3.建立Mapper接口

public interface StudentMapper {
}


public interface TeacherMapper {
@Select("select * from teacher where id = #{tid}")
Teacher getTeacher(@Param("id") int id);
}

4.建立Mapper,XML文件

image-20230606005122840

5.在核心配置文件中绑定注册我们的Mapper接口或者文件!【class】

<!--绑定接口-->
<mappers>
<mapper class="com.chen.dao.TeacherMapper"/>
<mapper class="com.chen.dao.StudentMapper"/>
</mappers>

6.测试查询是否能够成功!



  • 子查询

  • 联表查询

按照查询嵌套处理–子查询

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

<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>

<!--
·复杂的属性,需要单独处理 ·对象 association ·集合 collection
·javaType:指定属性类型
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>

</resultMap>


<!--where 子查询-->
<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.id tid,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="id" column="tid"/>-->
<result property="name" column="tname"/>
</association>

</resultMap>





一对多处理

  • mybatis-07

  • 一个对象对应多个对象

实体类

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

//拥有多个对象
private List<Student> students;
}

  • 集合中的泛型信息,我们使用ofType获取

按照查询嵌套处理–子查询

<!--按照查询嵌套-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatisb.teacher where id =#{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherID" column="id"/>
</resultMap>

<select id="getStudentByTeacherID" resultType="Student">
select id,name,tid from student where tid = #{tid}
</select>

按照结果嵌套查询

<!-- 按照结果嵌套 -->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where t.id=s.tid and t.id=#{tid}

</select>

<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--
·复杂的属性,需要单独处理 ·对象 association ·集合 collection
·javaType:指定属性的类型
·集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>

1.关联-association【多对一】
2.集合- collection【一对多】
3.javaType & of Type
1.JavaType:用来指定实体类中指定的类型 :(Teacher / ArrayList)
2.ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

面试高频

  • Mysql引擎

  • InnoDB底层原理

  • 索引

  • 索引优化!



联表查询总结

<resultMap id=" SQL标签的resultMap " type=" 类型 ">
<!--映射-->
<result property="映射的属性" column="数据库字段"/>

<!--对象:嵌套查询-->
<association property="映射的对象属性名" column="传递查询的主键" javaType="映射的对象类型" select="嵌套的SQL的id"/>
<!--集合:嵌套查询-->
<collection property="映射的对象属性名" javaType="ArrayList(本质上是一个集合)" ofType="泛型" select="嵌套的SQL的id" column="传递查询的主键"/>

<!--按结果查询-->
<collection property="students" ofType="Student">
<!--映射-->
</collection>

</resultMap>

  • association :对象【多对一】

    • javaType:指定属性类型

  • collection :集合【一对多】

    • ofType:用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!(如 List students –> List的类型为Stduent。则泛型为Student)





动态SQL

  • 设置随机ID
@SuppressWarnings("all") //过滤警告
public class IDutils {

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

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


1.导包

2.编写配置文件

<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启白动驼峰命名规则(camel case)映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

3.编写实休类

@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime; //属性名和字段名不一致
private int views;
}

4.靠写实体类对应Mapper接口和Mapper.XML文件

int addBlog(Blog blog);
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.dao.BlogMapper">

<insert id="addBlog" parameterType="blog">
insert into mybatisb.blog (id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>

</mapper>

5.test

Blog blog = new Blog();

blog.setId(IDutils.getId());
blog.setTitle("Mybatis.如此简单");
blog.setAuthor("CCCHEN");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);


IF

  • 传递 1 or 多值,根据这个字段找对应的记录,如果不传值则查询全部
  • 追加
 //mapper
//查询博客
List<Blog> queryBlogIf(Map map);



//xml
//追加拼接
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatisb.blog where 1=1
<if test="title!= null" >
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>


//test
HashMap map = new HashMap();
map.put("title","Mybatis如此简单");
//map.put("author","CCCHEN");
List<Blog> blogs =mapper.queryBlogIf(map);


trim(where,set)

where

  • where 元素只会在至少有一个子元素的条件返回SQL子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where元素也会将它们去除。

  • 使用拼接语句,在sql上不用添加where 1=1 :使用< where >

  • 当返回只有一个语句的时候,如果前面带 and / or ,会自动去除,

  • 多个则判断第一个语句返回有没有 and / or ,有则去除,

  • 使拼接后为 where 条件 and / or 条件

  • 如果条件为空,where 自动去除

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


set(更新)

set元素会动态前置SET关键字,同时也会删掉无关的逗号

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


Choose(when,otherwise)

选择:止步于当前满足的语句

<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatisb.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>


SQL片段

  • 提取各个部分,方便复用

1、使用SQL标签提提取,设置ID

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

注意事项:

  • 最好甚于单表来定义SQL片段!
  • 不要存在where语句

2、使用include标签引用

<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatisb.blog
<where>

<include refid="if-title-author"></include>

</where>
</select>


Foreach

select * from mybatisb.blog where 1=1 and (id=1 or id=2  or id=3)

image-20230606150417385

  • 以下拼接添加到sql语句中
  • collection:迭代的集合对象
  • item:遍历到的当前对象
  • open:开头
  • close:结尾
  • separator:迭代对象(分隔符)
<!--
原SQL:select * from mybatisb.blog where 1=1 and (id=1 or id=2 or id=3)

使用map传递一个集合

item="id" :遍历出来的局部变量
-->

<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatisb.blog
<where>
<foreach collection="ids" item="id" open=" and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>

  • test
List<Blog> queryBlogForeach(Map map);

HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);ids.add(2);
ids.add(3);ids.add(4);
map.put("ids",ids);
List<Blog> blogs=mapper.queryBlogForeach(map);


总结

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

建议:

  • 现在Mysq中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!





缓存

原理

image-20230723183308775



一级缓存

  • 小结:一级缓存默认是开启的,只在一次SglSession中有效,也就是学到连接到关闭连接这个区间段!
  • 一级缓存就是一个Map。
  • 清理一级缓存:sqlSession.clearCache()

image-20230606195638124

缓存失效的情况:

1.查询不同的东西

2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存!

3.查询不同的Mapper..xml

4.手动清理缓存!



二级缓存

  • 只需要在你的SQL映射文件中添加一行:

    <!--在当前Mapper.xml使用二级缓存-->
    <cache/>

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的煖存,一个名称空间,对应一个二级缓存:

  • 工作机制

    • 一个会话查询一条数,这个数把就会被放在当前会话的一级缓存中:

    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保有到二级缓存中

    • 新的会话查询信息,就可以从二级缓存中获取内容:

    • 不同的mapperj直出的数据会放在自己对应的媛存(map)中:


1、开启全局缓存

<!--显式的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>

2、在要使用二级缓存的Mapper .xml开启

<!--在当前Mapper.xml使用二级缓存-->
<cache/>

也可以自定义参数

<cache eviction="FIFO"
flushInterval="60000"
s1ze="512"
readon1y="true"/>

3、测试

image-20230723182628977



自定义缓存 Ehcache

Ehcache是一种广泛使用的开源]ava分布式缓存。主要面向通用缓存


依赖

<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>

在mappere中指定使用我们的ehcache缓存实现!

<!--在当前Mapper.xml中使用二级缓存-->
<cacheItype="org.mybatis.caches.ehcache.Ehcachecache"/>





项目总结

表上锁

  • 在执行中防止变动
  • sql 后 加 for update 排它锁
<!--查询用户余额:给uid的记录上锁(for update)-->
<select id="selectByUidForUpdate" resultMap="BaseResultMap">
select <include refid="Base_Column_List"></include>
from u_finance_account
where uid = #{uid}
for update
</select>


事务

  • 回滚
//方法上
@Transactional(rollbackFor = Exception.class)
//判断是否执行成功,否抛出异常触发回滚事务
if (rows < 1){
throw new RuntimeException("生成收益计划,更新产品状态为2失败");
}