mybatis

文章详细介绍了MyBatis的核心配置文件,包括环境、数据源、事务管理和SQL映射文件的配置。此外,还讨论了SQL映射文件中的元素,如select、insert、update、delete以及动态SQL的使用,如if、where、choose等标签。文章还提到了日志配置、别名设置、接口绑定以及MyBatis的一级和二级缓存机制。最后,resultMap的使用和多表查询的关联映射也被提及。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Myatis知识点

1.核心配置文件 mybatis.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">
<!-- mybatis的全局配置文件 -->
<configuration>
<!--
用于指明使用哪一个开发环境
default : 用于指定使用的环境的id属性值
-->
<environments default="ev">
<!-- 用户配置开发环境 id: 环境的唯一标识 -->
<environment id="ev">
<!--
事务管理器
JBDC : 表示采用JDBC一样的事务管理方式
-->
<transactionManager type="JDBC"/>
<!--
用于配置数据库连接吃和数据库连接参数
POOLED : 表示mybatis采用连接池技术
-->
<dataSource type="POOLED">
<property name="driver"
value="oracle.jdbc.driver.OracleDriver"/>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:XE"/>
<property name="username" value="SCOTT"/>
<property name="password" value="TIGER"/>
</dataSource>
</environment>
</environments>
<!-- SQL映射文件配置 -->
<mappers>
<!-- 指明SQL映射文件路径 resource : 包路径 com/.../xxxMapper.xml-->
<mapper resource="com/yjxxt/mappers/UserMapper.xml"/>
</mappers>
</configuration>
  1. sql 映射文件

<?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">
<!--
跟标签mapper
namespace: 命名空间-->
<mapper namespace="com.yjxxt.mappers.UserMapper">
<!--
查询标签: select 用于编写查询语句
id : 当前文件中保证唯一
resultType : 结果的类型
parameterType : 入参类型
-->
<select id="queryAll" resultType="com.yjxxt.pojo.User">
select * from t_user
</select>
</mapper>

注意:不要忘记mybatis核心xml文件中的mapper配置

3.SQL映射文件(mapper)

MyBatis 的真正强大在于它的映射语句,也是它的魔力所在。由于它的异常强大,映射器的 XML 文件就

显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代

码。MyBatis 就是针对 SQL 构建的,并且比普通的方法做的更好。

SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):

resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。

insert – 映射插入语句

update – 映射更新语句

delete – 映射删除语句

select – 映射查询语句

查询语句是 MyBatis 中最常用的元素之一(映射文件配置见代码)

4.三个查询方法

selectList(“命名空间.id”) 用户查询多条数据情况,返回一个List集合, 没有查到数据返回空集合,不是

null

selectOne(“命名空间.id”) 用于查询单条数据,返回一个数据, 如果没有查到返回null

selectMap(“命名空间.id”,key的字段名) 用于查询多条记录情况, 返回Map集合, 需要指定那个属性

作为key, sql查询结果作为value,指定的字段值作为key, 如果查不到, 返回一个空map集合,不是null

5.Log4J日志

DEBUG(人为调试信息)、INFO(普通信息)、WARN(警告)、ERROR(错误)和FATAL(系统错误)

这五个级别是有顺序的,DEBUG < INFO < WARN < ERROR < FATAL,分别用来指定这条日志信息的重要程度,明白这一点很重要,Log4j有一个规则:只输出级别不低于设定级别的日志信息,假设Logger级别设定为INFO,则INFO、WARN、ERROR和FATAL级别的日志信息都会输出,而级别比INFO低的DEBUG则不会输出。

5.1配置文件

# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=INFO, CONSOLE
# log4j.rootCategory=INFO, CONSOLE, LOGFILE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %m %c %l %d{yyyy-MMdd-HH:mm:ss}%n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/test.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n

# 提高整体日志级别
log4j.rootCategory=ERROR, CONSOLE
# 单独设置SQL语句的输出级别为DEBUG级别
# 方法级别
# log4j.logger.com.yjxxt.mapper.UserMapper.selAll=DEBUG
# 类级别
# log4j.logger.com.yjxxt.mapper.UserMapper=DEBUG
# 包级别
log4j.logger.com.yjxxt.mapper=DEBUG

5.2常见的日志输出格式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lOhXyV3u-1679573327986)(…/其他/其他文件/图片/1.bmp)]

5.3 开启支持

<!-- settings标签 -->
<settings>
<!-- 设置MyBatis使用log4j日志支持 -->
<setting name="logImpl" value="LOG4J"/>
</settings>

6.别名


<typeAliases>
<typeAlias type="com.yjxxt.pojo.User" alias="u"/>
</typeAliases>
------------------------------
<typeAliases>
<typeAlias type="com.yjxxt.pojo.User"/> alias属性不写,默认类名,不区分大小写
</typeAliases>
----------------------------
<typeAliases>
<package name="com.yjxxt.pojo"/> <!-- 包下所有的类默认类名 -->
</typeAliases>

7.接口绑定

​ Myabtis中,提供了一套接口绑定方案,程序员可以提供一个接口,然后提供一个与接口所对应的mapper.xml文件 Myabaits会自动将接口

与xml文件进行绑定,实际上就是Mybatis互根据接口和对应的xml文件创建一个接口的实现类,换言之,就是可以得到接口实现类的一个对象,

方便方法的调用

7.1 映射文件

注意:

  1. xml文件名要与接口名保持一致
  2. namespace属性值 必须与接口的权限定名
  3. id属性必须与抽象方法名保持一致
  4. 返回值类型和参数类型与方法的返回值和参数保持一致

7.2在核心配置文件中扫描接口

<!-- mapper 配置扫描接口 -->
<mappers>
<mapper class="com.yjxxt.mapper.UserMapper"/> <!--配置某个接口 -->
</mappers>
-----------------------------------
<!-- mapper 配置扫描接口 -->
<mappers>
<package name="com.yjxxt.mapper"/>
</mappers>

8.动态sql

8.1 if

​ 用于进行条件判断, test 属性用于指定判断条件. 为了拼接条件, 在 SQL 语句后强行添加 1=1 的恒成立条件

<select id="sel" resultType="user">
	select * from t_user where 1=1
	<if test="username != null and username != ''"> and username=#{username} </if>
	<if test="password != null and password != ''"> and password=#{password} </if>
</select>

8.2 where

用于管理 where 子句. 有如下功能:

  1. 如果没有条件, 不会生成 where 关键字
  2. 如果有条件, 会自动添加 where 关键字
  3. 如果第一个条件中有 and, 去除之
<select id="sel" resultType="user">
	select * from t_user
	<where>
		<if test="username != null and username != ''"> and username=#{username} </if>
		<if test="password != null and password != ''"> and password=#{password} </if>
	</where>
</select>

8.3 choose…when…otherwise

这是一套标签, 功能类似于 switch…case…

<select id="sel" resultType="user">
	select * from t_user
	<where>
		<choose>
			<when test="username != null and username != ''"> 
                and username = #{username} 
            </when>
			<when test="password != null and password != ''"> 
                and password = #{password} 
            </when>
			<otherwise> and 1=1 </otherwise>
		</choose>
	</where>
</select>

8.4 set

用于维护 update 语句中的 set 子句. 功能如下:

  1. 满足条件时, 会自动添加 set 关键字
  2. 会去除 set 子句中多余的逗号
  3. 不满足条件时, 不会生成 set 关键字
int updUser(User user);
<update id="updUser" parameterType="user">
	update t_user
	<set>
		 id=#{id},<!-- 防止所有条件不成立时的语法错误 -->
		<if test="username != null and username != ''">
			username=#{username},
		</if>
		<if test="password != null and password != ''">
            password=#{password}, 
        </if>
	</set>
	where id=#{id}
</update>

8.5 trim

用于在前后添加或删除一些内容

  1. prefix, 在前面添加内容
  2. prefixOverrides, 从前面去除内容
  3. suffix, 向后面添加内容
  4. suffixOverrides, 从后面去除内容
<update id="updUser" parameterType="user">
	update t_user 
    <!-- prefix: 前缀, 表示向前面添加内容 prefixOverrides: 从前面删除内容 suffix: 后缀, 表示向后面添加内容 suffixOverrides: 从后面删除内容 -->
	<trim prefix="set" prefixOverrides="user" suffix="hahaha"
		suffixOverrides=","> username=#{username}, 
    </trim>
	where id=#{id}
</update>

8.6 bind

用于对数据进行再加工, 用于模糊查询

<select id="sel" resultType="user">
	select * from t_user
	<where>
		<if test="username!=null and username!=''">
			<bind name="username" value="'%' + username + '%'" />
			and username like #{username}
		</if>
	</where>
</select>

8.7 foreach

用于在 SQL 语句中遍历集合参数, 在 in 查询中使用

  1. collection: 待遍历的集合
  2. open: 设置开始符号
  3. item: 迭代变量
  4. separator: 项目分隔符
  5. close: 设置结束符
List<User> selIn(@Param("list") List<Integer> list);
<select id="selIn" parameterType="list" resultType="user">
	select * from t_user where id in
	<foreach collection="list" open="(" separator="," close=")"
		item="item"> #{item} </foreach>
</select>

8.8 sql…include

sql用于提取 SQL 语句, include用于引用 SQL 语句

<sql id="mySql"> id, username, password </sql>
<select id="selIn" parameterType="list" resultType="user">
	select
	<include refid="mySql" />
	from t_user where id in
	<foreach collection="list" open="(" separator="," close=")"
		item="item"> #{item}
	</foreach>
</select>

9.mybatis缓存

​ 缓存的重要性是不言而喻的。 使用缓存, 我们可以避免频繁的与数据库进行交互, 尤其是在查询越多、缓存命中率越高的情况下,

使用缓存对性能的提高更明显。mybatis 也提供了对缓存的支持, 分为一级缓存和二级缓存。 但是在默认的情况下, 只开启一级缓存。

9.1. 一级缓存

\1. 默认开启. 线程级别的缓存, SqlSession 的缓存;

\2. 在一个 SqlSession 生命周期中有效. SqlSession 关闭,缓存清空;

\3. 在同一个 SqlSession 中, Mybatis 会把执行的方法和参数通过算法生成缓存的键值, 将键值和结果

存放在一个 Map 中, 如果后续的键值一样, 则直接从 Map 中获取数据;

\4. 不同的 SqlSession 之间的缓存是相互隔离的;

\5. 用一个 SqlSession, 可以通过配置使得在查询前清空缓存;flushCache=“true”

\6. 任何的 UPDATE, INSERT, DELETE 语句都会清空缓存。

9.2 二级缓存

\1. 进程级别的缓存, SqlSessionFactory 的缓存

\2. 在一个SqlSessionFactory生命周期中有效. 可以在多个SqlSession 生命中期中共享.

\3. 默认关闭, 需要使用的时候, 要为某个命名空间开启二级缓存(在 mapper.xml 中配置cache).

\4. 由于在更新时会刷新缓存, 因此需要注意使用场合:查询频率很高, 更新频率很低时使用, 即经常使用 select, 相对较少使用delete,

insert, update。

\5. 缓存是以 namespace 为单位的,不同 namespace 下的操作互不影响。但刷新缓存是刷新整个namespace 的缓存, 也就是你 update

了一个, 则整个缓存都刷新了。

\6. 最好在 「只有单表操作」 的表的 namespace 使用缓存, 而且对该表的操作都在这个 namespace中。 否则可能会出现数据不一致的

情况。

二级缓存应用场景:

====对于访问多的查询请求并且用户对查询结果实时性要求不高的情况下,可采用mybatis二级缓存,降低数据库访问量,提高访问速

度,如电话账单查询 根据需求设置相应的flushInterval:刷新间隔时间,比如三十分钟,24小时等。。

10.resultMap

​ resultMap用于自定义映射关系, 可以由程序员自主制定列名和属性名的映射关系. 一旦使用 resultMap,

表示不再采用自动映射机制.

<resultMap type="user" id="umap">
<!-- id用于映射主键 -->
<id column="id" property="id1" />
<!-- 非主键使用result映射 -->
<result column="username" property="username1" />
<result column="password" property="password1" />
</resultMap>
<select id="selAll" resultMap="umap"> select * from t_user </select>

10.1 resultMap 的关联方式实现多表查询(一对一|多对一)

\1. 在 StudentMapper.xml 中定义多表连接查询 SQL 语句, 一次性查到需要的所有数据, 包括对应班级的信息.

\2. 通过resultMap标签定义映射关系, 并通过association标签指定对象属性的映射关系. 可以把association标签看成一个resultMap标签使

用. javaType 属性表示当前对象, 可以写全限定路径或别名.

<resultMap type="student" id="smap">
<id property="id" column="sid" />
<result property="name" column="sname" />
<result property="age" column="age" />
<result property="gender" column="gender" />
<result property="cid" column="cid" />
<association property="cls" javaType="clazz">
<id property="id" column="cid" />
<result property="name" column="cname" />
<result property="room" column="room" />
</association>
</resultMap>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值