【轉載】springboot:如何優雅的使用mybatis

這兩天啟動了一個新項目因為項目組成員一直都使用的是mybatis,雖然個人比較喜歡jpa這種極簡的模式,但是為了項目保持統一性技術選型還是定了 mybatis。到網上找了一下關于spring boot和mybatis組合的相關資料,各種各樣的形式都有,看的人心累,結合了mybatis的官方demo和文檔終于找到了最簡的兩種模式,花了一天時間總結后分享出來。

orm框架的本質是簡化編程中操作數據庫的編碼,發展到現在基本上就剩兩家了,一個是宣稱可以不用寫一句SQL的hibernate,一個是可以靈活調試動態sql的mybatis,兩者各有特點,在企業級系統開發中可以根據需求靈活使用。發現一個有趣的現象:傳統企業大都喜歡使用hibernate,互聯網行業通常使用mybatis。

hibernate特點就是所有的sql都用Java代碼來生成,不用跳出程序去寫(看)sql,有著編程的完整性,發展到最頂端就是spring data jpa這種模式了,基本上根據方法名就可以生成對應的sql了,有不太了解的可以看我的上篇文章springboot(五):spring data jpa的使用。

mybatis初期使用比較麻煩,需要各種配置文件、實體類、dao層映射關聯、還有一大推其它配置。當然mybatis也發現了這種弊端,初期開發了generator可以根據表結果自動生產實體類、配置文件和dao層代碼,可以減輕一部分開發量;后期也進行了大量的優化可以使用注解了,自動管理dao層和配置文件等,發展到最頂端就是今天要講的這種模式了,mybatis-spring-boot-starter就是springboot+mybatis可以完全注解不用配置文件,也可以簡單配置輕松上手。

mybatis-spring-boot-starter

官方說明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
其實就是myBatis看spring boot這么火熱也開發出一套解決方案來湊湊熱鬧,但這一湊確實解決了很多問題,使用起來確實順暢了許多。mybatis-spring-boot-starter主要有兩種解決方案,一種是使用注解解決一切問題,一種是簡化后的老傳統。

當然任何模式都需要首先引入mybatis-spring-boot-starter的pom文件,現在最新版本是1.1.1

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version>
</dependency>

好了下來分別介紹兩種開發模式

無配置文件注解版

就是一切使用注解搞定。

1 添加相關maven文件

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>
</dependencies>

完整的pom包這里就不貼了,大家直接看源碼

2、application.properties 添加相關配置

mybatis.type-aliases-package=com.neo.entityspring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root

springboot會自動加載spring.datasource.*相關配置,數據源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,對了你一切都不用管了,直接拿起來使用就行了。

在啟動類中添加對mapper包掃描@MapperScan

@SpringBootApplication
@MapperScan("com.neo.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

或者直接在Mapper類上面添加注解@Mapper,建議使用上面那種,不然每個mapper加個注解也挺麻煩的

3、開發Mapper

第三步是最關鍵的一塊,sql生產都在這里

public interface UserMapper {@Select("SELECT * FROM users")@Results({@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name")})List<UserEntity> getAll();@Select("SELECT * FROM users WHERE id = #{id}")@Results({@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),@Result(property = "nickName", column = "nick_name")})UserEntity getOne(Long id);@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")void insert(UserEntity user);@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")void update(UserEntity user);@Delete("DELETE FROM users WHERE id =#{id}")void delete(Long id);}

為了更接近生產我特地將user_sex、nick_name兩個屬性在數據庫加了下劃線和實體類屬性名不一致,另外user_sex使用了枚舉

@Select 是查詢類的注解,所有的查詢均使用這個
@Result 修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,如果實體類屬性和數據庫屬性名保持一致,就不需要這個屬性來修飾。
@Insert 插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值
@Update 負責修改,也可以直接傳入對象
@delete 負責刪除
// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

4、使用

上面三步就基本完成了相關dao層開發,使用的時候當作普通的類注入進入就可以了

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper UserMapper;@Testpublic void testInsert() throws Exception {UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));Assert.assertEquals(3, UserMapper.getAll().size());}@Testpublic void testQuery() throws Exception {List<UserEntity> users = UserMapper.getAll();System.out.println(users.toString());}@Testpublic void testUpdate() throws Exception {UserEntity user = UserMapper.getOne(3l);System.out.println(user.toString());user.setNickName("neo");UserMapper.update(user);Assert.assertTrue(("neo".equals(UserMapper.getOne(3l).getNickName())));}
}

極簡xml版本

極簡xml版本保持映射文件的老傳統,優化主要體現在不需要實現dao的是實現層,系統會自動根據方法名在映射文件中找對應的sql.

1、配置

pom文件和上個版本一樣,只是application.properties新增以下配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

指定了mybatis基礎配置文件和實體類映射文件的地址

mybatis-config.xml 配置

<configuration><typeAliases><typeAlias alias="Integer" type="java.lang.Integer" /><typeAlias alias="Long" type="java.lang.Long" /><typeAlias alias="HashMap" type="java.util.HashMap" /><typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" /><typeAlias alias="ArrayList" type="java.util.ArrayList" /><typeAlias alias="LinkedList" type="java.util.LinkedList" /></typeAliases>
</configuration>

這里也可以添加一些mybatis基礎的配置

2、添加User的映射文件

<mapper namespace="com.neo.mapper.UserMapper" ><resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" ><id column="id" property="id" jdbcType="BIGINT" /><result column="userName" property="userName" jdbcType="VARCHAR" /><result column="passWord" property="passWord" jdbcType="VARCHAR" /><result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/><result column="nick_name" property="nickName" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, userName, passWord, user_sex, nick_name</sql><select id="getAll" resultMap="BaseResultMap"  >SELECT <include refid="Base_Column_List" />FROM users</select><select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM usersWHERE id = #{id}</select><insert id="insert" parameterType="com.neo.entity.UserEntity" >INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})</insert><update id="update" parameterType="com.neo.entity.UserEntity" >UPDATE users SET <if test="userName != null">userName = #{userName},</if><if test="passWord != null">passWord = #{passWord},</if>nick_name = #{nickName}WHERE id = #{id}</update><delete id="delete" parameterType="java.lang.Long" >DELETE FROMusers WHERE id =#{id}</delete>
</mapper>

其實就是把上個版本中mapper的sql搬到了這里的xml中了

3、編寫Dao層的代碼

public interface UserMapper {List<UserEntity> getAll();UserEntity getOne(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}

對比上一步這里全部只剩了接口方法

4、使用

使用和上個版本沒有任何區別,大家就看代碼吧

如何選擇

兩種模式各有特點,注解版適合簡單快速的模式,其實像現在流行的這種微服務模式,一個微服務就會對應一個自已的數據庫,多表連接查詢的需求會大大的降低,會越來越適合這種模式。

老傳統模式比適合大型項目,可以靈活的動態生成SQL,方便調整SQL,也有痛痛快快,洋洋灑灑的寫SQL的感覺。

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390242.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390242.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390242.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

創建react應用程序_通過構建電影搜索應用程序在1小時內了解React

創建react應用程序If youve been meaning to learn React but are unsure of where to start, Scrimbas brand new Build a Movie Search App course is perfect for you! 如果您一直想學習React&#xff0c;但是不確定從哪里開始&#xff0c;那么Scrimba全新的Build a Movie S…

GeoServer自動發布地圖服務

1 NetCDF氣象文件自動發布案例 GeoServer是一個地理服務器&#xff0c;提供了管理頁面進行服務發布&#xff0c;樣式&#xff0c;切片&#xff0c;圖層預覽等一系列操作&#xff0c;但是手動進行頁面配置有時并不滿足業務需求&#xff0c;所以GeoServer同時提供了豐富的rest接口…

selenium+ python自動化--斷言assertpy

前言&#xff1a; 在對登錄驗證時&#xff0c;不知道為何原因用unittest的斷言不成功&#xff0c;就在網上發現這個assertpy&#xff0c;因此做個筆記 準備&#xff1a; pip install assertypy 例子&#xff1a; 1 from assertpy import assert_that2 3 4 def check_login():5 …

11. 盛最多水的容器

11. 盛最多水的容器 給你 n 個非負整數 a1&#xff0c;a2&#xff0c;…&#xff0c;an&#xff0c;每個數代表坐標中的一個點 (i, ai) 。在坐標內畫 n 條垂直線&#xff0c;垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0) 。找出其中的兩條線&#xff0c;使得它們與 x 軸共同構…

深入理解ES6 pdf

下載地址&#xff1a;網盤下載目錄 第1章 塊級作用域綁定 1var聲明及變量提升&#xff08;Hoisting&#xff09;機制 1塊級聲明 3-- let聲明 3-- 禁止重聲明 4-- const聲明 4-- 臨時死區&#xff08;Temporal Dead Zone&#xff09; 6循環中的塊作用域綁定 7-- 循環中的函…

MyBatis之輸入與輸出(resultType、resultMap)映射

2019獨角獸企業重金招聘Python工程師標準>>> 在MyBatis中&#xff0c;我們通過parameterType完成輸入映射(指將值映射到sql語句的占位符中&#xff0c;值的類型與dao層響應方法的參數類型一致)&#xff0c;通過resultType完成輸出映射(從數據庫中輸出&#xff0c;通…

2021-08-25556. 下一個更大元素 III

556. 下一個更大元素 III 給你一個正整數 n &#xff0c;請你找出符合條件的最小整數&#xff0c;其由重新排列 n 中存在的每位數字組成&#xff0c;并且其值大于 n 。如果不存在這樣的正整數&#xff0c;則返回 -1 。 注意 &#xff0c;返回的整數應當是一個 32 位整數 &…

gradle tool升級到3.0注意事項

Gradle版本升級 其實當AS升級到3.0之后&#xff0c;Gradle Plugin和Gradle不升級也是可以繼續使用的&#xff0c;但很多新的特性如&#xff1a;Java8支持、新的依賴匹配機制、AAPT2等新功能都無法正常使用。 Gradle Plugin升級到3.0.0及以上&#xff0c;修改project/build.grad…

如何使用React,TypeScript和React測試庫創建出色的用戶體驗

Im always willing to learn, no matter how much I know. As a software engineer, my thirst for knowledge has increased a lot. I know that I have a lot of things to learn daily.無論我知道多少&#xff0c;我總是愿意學習。 作為軟件工程師&#xff0c;我對知識的渴望…

PowerDesigner常用設置

2019獨角獸企業重金招聘Python工程師標準>>> 使用powerdesigner進行數據庫設計確實方便&#xff0c;以下是一些常用的設置 附加&#xff1a;工具欄不見了 調色板(Palette)快捷工具欄不見了 PowerDesigner 快捷工具欄 palette 不見了&#xff0c;怎么重新打開&#x…

bzoj5090[lydsy11月賽]組題

裸的01分數規劃,二分答案,沒了. #include<cstdio> #include<algorithm> using namespace std; const int maxn100005; int a[maxn]; double b[maxn]; double c[maxn]; typedef long long ll; ll gcd(ll a,ll b){return (b0)?a:gcd(b,a%b); } int main(){int n,k;s…

797. 所有可能的路徑

797. 所有可能的路徑 給你一個有 n 個節點的 有向無環圖&#xff08;DAG&#xff09;&#xff0c;請你找出所有從節點 0 到節點 n-1 的路徑并輸出&#xff08;不要求按特定順序&#xff09; 二維數組的第 i 個數組中的單元都表示有向圖中 i 號節點所能到達的下一些節點&#…

深入框架本源系列 —— Virtual Dom

該系列會逐步更新&#xff0c;完整的講解目前主流框架中底層相通的技術&#xff0c;接下來的代碼內容都會更新在 這里 為什么需要 Virtual Dom 眾所周知&#xff0c;操作 DOM 是很耗費性能的一件事情&#xff0c;既然如此&#xff0c;我們可以考慮通過 JS 對象來模擬 DOM 對象&…

網絡工程師常備工具_網絡安全工程師應該知道的10種工具

網絡工程師常備工具If youre a penetration tester, there are numerous tools you can use to help you accomplish your goals. 如果您是滲透測試人員&#xff0c;則可以使用許多工具來幫助您實現目標。 From scanning to post-exploitation, here are ten tools you must k…

configure: error: You need a C++ compiler for C++ support.

安裝pcre包的時候提示缺少c編譯器 報錯信息如下&#xff1a; configure: error: You need a C compiler for C support. 解決辦法&#xff0c;使用yum安裝&#xff1a;yum -y install gcc-c 轉載于:https://www.cnblogs.com/mkl34367803/p/8428264.html

程序編寫經驗教訓_編寫您永遠都不會忘記的有效績效評估的經驗教訓。

程序編寫經驗教訓This article is intended for two audiences: people who need to write self-evaluations, and people who need to provide feedback to their colleagues. 本文面向兩個受眾&#xff1a;需要編寫自我評估的人員和需要向同事提供反饋的人員。 For the purp…

刪除文件及文件夾命令

方法一&#xff1a; echo off ::演示&#xff1a;刪除指定路徑下指定天數之前&#xff08;以文件的最后修改日期為準&#xff09;的文件。 ::如果演示結果無誤&#xff0c;把del前面的echo去掉&#xff0c;即可實現真正刪除。 ::本例需要Win2003/Vista/Win7系統自帶的forfiles命…

BZOJ 3527: [ZJOI2014]力(FFT)

題意 給出\(n\)個數\(q_i\),給出\(Fj\)的定義如下&#xff1a; \[F_j\sum \limits _ {i < j} \frac{q_iq_j}{(i-j)^2}-\sum \limits _{i >j} \frac{q_iq_j}{(i-j)^2}.\] 令\(E_iF_i/q_i\)&#xff0c;求\(E_i\). 題解 一開始沒發現求\(E_i\)... 其實題目還更容易想了... …

c# 實現刷卡_如何在RecyclerView中實現“刷卡選項”

c# 實現刷卡Lets say a user of your site wants to edit a list item without opening the item and looking for editing options. If you can enable this functionality, it gives that user a good User Experience. 假設您網站的用戶想要在不打開列表項并尋找編輯選項的情…

批處理命令無法連續執行

如題&#xff0c;博主一開始的批處理命令是這樣的&#xff1a; cd node_modules cd heapdump node-gyp rebuild cd .. cd v8-profiler-node8 node-pre-gyp rebuild cd .. cd utf-8-validate node-gyp rebuild cd .. cd bufferutil node-gyp rebuild pause執行結果&#xff1…