mybatis的4种Mapper注册方式

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<mappers>  
		<!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 -->  
		<package name="com.tiantian.mybatis.mapperinterface"/>  
		<!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 -->  
		<mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/>  
		<!-- 通过mapper元素的url属性可以指定一个通过URL请求道的Mapper.xml文件 -->  
		<mapper url="file:///E:/UserMapper.xml"/>  
		<!-- 通过mapper元素的class属性可以指定一个Mapper接口进行注册 -->  
		<mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/>  
	</mappers>  
</configuration>

MyBatismapper注册是指将mapper接口和对应的SQL映射文件关联起来,使得MyBatis能够识别和执行对应的SQL语句。注册mapper主要有两方式:注解方式和配置文件方式。 1. 注解方式:在mapper接口上使用MyBatis提供的注解,如`@Mapper`,然后在SQL映射文件中使用`<mapper>`标签指定namespace为该接口的全限定名,并且在文件中使用相同namespace的SQL语句。这方式简单,但不适用于较为复杂的SQL映射。 2. 配置文件方式:通过MyBatis的配置文件(如mybatis-config.xml)进行配置。在配置文件中使用`<mappers>`标签包含一个或多个`<mapper>`子标签,每个`<mapper>`可以指定一个SQL映射文件的路径,或者指定一个mapper接口的全限定名。这样,MyBatis在启动时会自动扫描并注册指定的mapper。 具体的配置示例如下: 使用XML配置文件方式注册mapper的示例: ```xml <!-- mybatis-config.xml --> <configuration> <!-- ... 其他配置 ... --> <mappers> <!-- 注册一个SQL映射文件 --> <mapper resource="org/mybatis/example/BlogMapper.xml"/> <!-- 或者直接注册一个mapper接口 --> <mapper class="org.mybatis.example.BlogMapper"/> </mappers> </configuration> ``` 使用注解注册mapper接口的示例: ```java // BlogMapper.java @Mapper public interface BlogMapper { // ... mapper接口的方法定义 ... } ``` 然后,通常需要在MyBatis的配置文件中指定扫描该接口所在的包: ```xml <!-- mybatis-config.xml --> <configuration> <!-- ... 其他配置 ... --> <mappers> <!-- 扫描包 --> <package name="org.mybatis.example"/> </mappers> </configuration> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0X码上链

你的鼓将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值