Mybatis进阶用法详解

这篇博客详细介绍了Mybatis的进阶配置,包括SqlMapConfig.xml中的配置元素,如properties、typeAliases等,并强调了重要部分。此外,文章还讲解了动态SQL的If标签在多条件查询中的应用,以及Mybatis逆向工程生成Mapper接口、映射文件和POJO类的过程,以及其限制和注意事项。

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

一.mybatis主配置文件SqlMapConfig.xml进阶配置

SqlMapConfig.xml中配置文件的内容和顺序如下:(数字代表层级)

properties(属性)
settings(全局配置参数)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境集合属性对象)
(2)environment(环境子属性对象)
(3)transactionManager(事务管理)
(3)dataSource(数据源)
mappers(映射器)

标注粗体的个人认为比较重要,故在此记录。

1.properties属性:可以用来引用外部的属性配置文件,常见的有数据库信息的配置文件db.properties,引用如下:

	<!-- 是用resource属性加载外部配置文件 -->
	<properties resource="db.properties">
		<!-- 在properties内部用property定义属性 -->
		<!-- 如果外部配置文件有该属性,则内部定义属性被外部属性覆盖 -->
		<property name="jdbc.username" value="root123" />
		<property name="jdbc.password" value="root123" />
	</properties>

引用此文件过后,即可在数据源配置中引用,解决硬编码问题。

2.typeAliases:类型别名,可以用来简化在SQL映射文件中输入输出参数的书写,且别名大小写不敏感。mybatis内置的支持别名列表如下:

别名 映射的类型
_byte byte 
_long long 
_short short 
_int int 
_integer int 
_double double 
_float float 
_boolean boolean 
string String 
byte Byte 
long Long 
short Short 
int Integer 
integer Integer 
double Double 
float Float 
boolean Boolean 
date Date 
decimal BigDecimal 
bigdecimal BigDecimal 
map Map
用户也可以自定义别名,语法如下:可以单个定义,可以使用扫描包的方式定义

<typeAliases>
		<!-- 单个别名定义 -->
		<typeAlias alias="user" type="com.cai.mybatis.pojo.User" />
		<!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
		<package name="com.cai.mybatis.pojo" />
		<package name="其它包" />
	</typeAliases>

3.mapper映射器:用来在mybatis主配置文件中引入SQL映射文件,总共有三种引入形式。

第一种:<mapper resource=" " />,使用相对于类路径的资源,如:<mapper resource="sqlmap/User.xml" />

(后面两种在动态代理开发方式中使用,接下来讲解)

第二种: <mapper class=" " />,使用mapper接口类路径,<mapperclass="com.cai.mybatis.mapper.UserMapper"/>

第三种: <package name=""/>,注册指定包下的所有mapper接口如:<package name="com.cai.mybatis.mapper"/>
注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。


二.SQL映射文件进阶配置--动态SQL

1.If标签:可用来为多条件查询时做非空校验

<!-- 根据条件查询用户 -->
<select id="queryUserByWhere" parameterType="user" resultType="user">
	SELECT id, username, birthday, sex, address FROM `user`
<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 -->
	<where>
		<if test="sex != null">
			AND sex = #{sex}
		</if>
		<if test="username != null and username != ''">
			AND username LIKE
			'%${username}%'
		</if>
	</where>
</select>
2.SQL片段:可将重复的SQL抽取出来,使用时用include引用即可,以达到SQL重用的目的

<!-- 根据条件查询用户 -->
<select id="queryUserByWhere" parameterType="user" resultType="user">
	<!-- SELECT id, username, birthday, sex, address FROM `user` -->
	<!-- 使用include标签加载sql片段;refid是sql片段id -->
	SELECT <include refid="userFields" /> FROM `user`
	<!-- where标签可以自动添加where关键字,同时处理sql语句中第一个and关键字 -->
	<where>
		<if test="sex != null">
			AND sex = #{sex}
		</if>
		<if test="username != null and username != ''">
			AND username LIKE
			'%${username}%'
		</if>
	</where>
</select>

<!-- 声明sql片段 -->
<sql id="userFields">
	id, username, birthday, sex, address
</sql>
3.foreach标签:向sql传递数组或者list,mybatis使用foreach解析,例如:传入的queryVo具有一个id的list集合

<!-- 根据ids查询用户 -->
<select id="queryUserByIds" parameterType="queryVo" resultType="user">
	SELECT * FROM `user`
	<where>
		<!-- foreach标签,进行遍历 -->
		<!-- collection:遍历的集合,这里是QueryVo的ids属性 -->
		<!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
		<!-- open:在前面添加的sql片段 -->
		<!-- close:在结尾处添加的sql片段 -->
		<!-- separator:指定遍历的元素之间使用的分隔符 -->
		<foreach collection="ids" item="item" open="id IN (" close=")"
			separator=",">
			#{item}
		</foreach>
	</where>
</select>

三.Mybatis使用方式进阶--mapper动态代理接口方式

1.开发规范说明:Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同 
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
步骤一:重定义SQL映射文件,UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:命名空间,用于隔离sql -->
<!-- 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.cai.mybatis.mapper.UserMapper">
	<!-- 根据用户id查询用户 -->
	<!-- 2. id必须和Mapper接口方法名一致 -->
	<!-- 3. parameterType必须和接口方法参数类型一致 -->
	<!-- 4. resultType必须和接口方法返回值类型一致 -->
	<select id="queryUserById" parameterType="int"
		resultType="com.cai.mybatis.pojo.User">
		select * from user where id = #{id}
	</select>
步骤二:定义一个与SQL映射文件相对应的UserMapper接口
public interface UserMapper {
	/**
	 * 根据id查询
	 */
	User queryUserById(int id);
}
步骤三:在主配置文件SqlMapConfig.xml文件中加载SQL映射文件
<!-- 加载映射文件 -->
	<mappers>
		<mapper resource="mapper/UserMapper.xml" />
	</mappers>
小结:使用动态接口开发具有很多的好处,mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。开发者直接通过接口调用方法即可。

四.mybatis进阶--mybatis逆向工程

mybatis官方提供了Mapper自动生成工具,可以通过配置generator.xml文件,根据数据库表自动生成pojo类和mapper映射文件,接口文件。配置文件定义如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">


<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="root">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
userId="yycg" password="yycg"> </jdbcConnection> -->


<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>


<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.cai.ssm.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.cai.ssm.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itcast.ssm.mapper" targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="user"></table>
</context>
</generatorConfiguration>

基本上,开发者只需要改动上述文件的四处标注红色部分,执行main主函数后既可以根据自己的数据库表自动生成pojo类和mapper映射文件和接口文件。但是需要特别注意一下两点:

1. 逆向工程生成的代码只能做单表查询
2. 不能在生成的代码上进行扩展,因为如果数据库变更,需要重新使用逆向工程生成代码,原来编写的代码就被覆盖了。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值