MyBatis中的@Mapper注解及配套注解使用详解

7978 2026-01-23 16:38:03

https://blog.csdn.net/phenomenonstell/article/details/79033144

从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的蛋疼。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释现在我们通过一个简易的maven项目去了解@Mapper注解的使用方式完整项目请访问我的github项目地址下载1、构建一个maven的web项目,目录结构如下:

2、导入相应的依赖

org.mybatis

mybatis

3.4.5

org.mybatis

mybatis-spring

1.3.1

org.springframework

spring-webmvc

5.0.2.RELEASE

org.springframework

spring-tx

5.0.2.RELEASE

org.apache.logging.log4j

log4j-core

2.7

com.alibaba

druid

1.1.6

org.springframework

spring-jdbc

5.0.2.RELEASE

mysql

mysql-connector-java

6.0.6

3、代码

//UserDAO

import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

import entity.User;

/**

* 添加了@Mapper注解之后这个接口在编译时会生成相应的实现类

*

* 需要注意的是:这个接口中不可以定义同名的方法,因为会生成相同的id

* 也就是说这个接口是不支持重载的

*/

@Mapper

public interface UserDAO {

@Select("select * from user where name = #{name}")

public User find(String name);

@Select("select * from user where name = #{name} and pwd = #{pwd}")

/**

* 对于多个参数来说,每个参数之前都要加上@Param注解,

* 要不然会找不到对应的参数进而报错

*/

public User login(@Param("name")String name, @Param("pwd")String pwd);

}

测试类代码:

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import dao.UserDAO;

import entity.User;

public class TestCase {

@Test

public void testMapper() {

ApplicationContext ac = new ClassPathXmlApplicationContext("spring-mybatis.xml");

UserDAO dao = ac.getBean(UserDAO.class);

User u1 = dao.find("hehe");

User u2 = dao.login("hehe", "123");

System.out.println(u1.getName().equals(u2.getName()));

}

}

测试结果:

c语言如何读写xml文件内容
系统还原软件,有哪些?几款常见的系统还原/系统保护软件对比 - 冰点还原精灵官方网站