https://blog.csdn.net/phenomenonstell/article/details/79033144
从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的蛋疼。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释
现在我们通过一个简易的maven项目去了解@Mapper注解的使用方式
完整项目请访问我的github项目地址下载
1、构建一个maven的web项目,目录结构如下:
2、导入相应的依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
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()));
}
}
测试结果: