MyBatis中的@Mapper注解及配套注解使用详解
生活随笔
收集整理的這篇文章主要介紹了
MyBatis中的@Mapper注解及配套注解使用详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 {@Testpublic 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()));} }測試結果:
?
轉載于:https://www.cnblogs.com/arrows/p/10531808.html
總結
以上是生活随笔為你收集整理的MyBatis中的@Mapper注解及配套注解使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何选择最佳技术来加速文件传输!
- 下一篇: 电脑回收站删除的文件怎么恢复,原来这么简