mybatis @Mapper注解

作用

从mybatis3.4.0开始加入了@Mapper注解,目的就是为了 不再写 mapper映射文件

例子

//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()));
    }
}

原文出处:/show_1EF6MdFIKBej.html