MyBatis中的@Mapper注解及配套注解使用详解
https://blog.csdn.net/phenomenonstell/article/details/79033144
从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的蛋疼。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释现在我们通过一个简易的maven项目去了解@Mapper注解的使用方式完整项目请访问我的github项目地址下载1、构建一个maven的web项目,目录结构如下:
2、导入相应的依赖
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()));
}
}
测试结果: