日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

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

發(fā)布時間:2025/6/15 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis中的@Mapper注解及配套注解使用详解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

?

從mybatis3.4.0開始加入了@Mapper注解,目的就是為了不再寫mapper映射文件(那個xml寫的是真的蛋疼。。。)。很惡心的一個事實(shí)是源碼中并沒有對于這個注解的詳細(xì)解釋
現(xiàn)在我們通過一個簡易的maven項(xiàng)目去了解@Mapper注解的使用方式
完整項(xiàng)目請?jiān)L問我的github項(xiàng)目地址下載
1、構(gòu)建一個maven的web項(xiàng)目,目錄結(jié)構(gòu)如下:

2、導(dǎo)入相應(yīng)的依賴

<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注解之后這個接口在編譯時會生成相應(yīng)的實(shí)現(xiàn)類* * 需要注意的是:這個接口中不可以定義同名的方法,因?yàn)闀上嗤膇d* 也就是說這個接口是不支持重載的*/ @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}")/*** 對于多個參數(shù)來說,每個參數(shù)之前都要加上@Param注解,* 要不然會找不到對應(yīng)的參數(shù)進(jìn)而報(bào)錯*/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()));} }

測試結(jié)果:

?

轉(zhuǎn)載于:https://www.cnblogs.com/arrows/p/10531808.html

總結(jié)

以上是生活随笔為你收集整理的MyBatis中的@Mapper注解及配套注解使用详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。