優雅的使用mybatis
mybatis初期使用比較麻煩,需要各種設定檔、實體類別、dao層映射關聯、還有一大推其它配置。當然mybatis也發現了這種弊端,初期開發了generator可以根據表結果自動生產實體類、設定檔和dao層程式碼,可以減輕一部分開發量;後期也進行了大量的優化可以使用註解了,自動管理dao層和設定檔等,發展到最頂端就是今天要講的這種模式了,mybatis-spring-boot-starter就是springboot+mybatis可以完全註解不用設定文件,也可以簡單設定輕鬆上手。
現在想想spring boot 就是牛鼻呀,任何東西只要關聯到spring boot都是化繁為簡。
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.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = root spring.datasource.password = root
springbootoot會自動載入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); }
注意,使用#符號和$符號的不同:
// 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)@SpringBootTestpublic class UserMapperTest { @Autowired private UserMapper UserMapper; @Test public 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()); } @Test public void testQuery() throws Exception { List<UserEntity> users = UserMapper.getAll(); System.out.println(users.toString()); } @Test public 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.xm
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 users WHERE 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 FROM users 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); }
对比上一步这里全部只剩了接口方法
如何选择
两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。
老传统模式比适合大型项目,可以灵活的动态生成SQL,方便调整SQL,也有痛痛快快,洋洋洒洒的写SQL的感觉。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

iBatis與MyBatis:你該選擇哪一個?簡介:隨著Java語言的快速發展,許多持久化框架也應運而生。 iBatis和MyBatis是兩個備受歡迎的持久化框架,它們都提供了一個簡單而高效的資料存取解決方案。本文將介紹iBatis和MyBatis的特點和優勢,並給出一些具體的程式碼範例,幫助你選擇合適的框架。 iBatis簡介:iBatis是一個開源的持久化框架

JPA和MyBatis:功能與效能比較分析引言:在Java開發中,持久化框架扮演著非常重要的角色。常見的持久化框架包括JPA(JavaPersistenceAPI)和MyBatis。本文將對這兩個框架的功能和效能進行比較分析,並提供具體的程式碼範例。一、功能對比:JPA:JPA是JavaEE的一部分,提供了一個物件導向的資料持久化解決方案。它透過註解或X

MyBatis動態SQL標籤解讀:Set標籤用法詳解MyBatis是一個優秀的持久層框架,它提供了豐富的動態SQL標籤,可以靈活地建構資料庫操作語句。其中,Set標籤是用來產生UPDATE語句中SET子句的標籤,在更新作業中非常常用。本文將詳細解讀MyBatis中Set標籤的用法,以及透過具體的程式碼範例來示範其功能。什麼是Set標籤Set標籤用於MyBati

MyBatis中實現批量刪除語句的幾種方式,需要具體程式碼範例近年來,由於資料量的不斷增加,批量操作成為了資料庫操作的一個重要環節之一。在實際開發中,我們經常需要批量刪除資料庫中的記錄。本文將重點介紹在MyBatis中實作批量刪除語句的幾種方式,並提供相應的程式碼範例。使用foreach標籤實作批量刪除MyBatis提供了foreach標籤,可以方便地遍歷一個集

MyBatis批量刪除語句的使用方法詳解,需要具體程式碼範例引言:MyBatis是一款優秀的持久層框架,提供了豐富的SQL操作功能。在實際專案開發中,經常會遇到需要大量刪除資料的情況。本文將詳細介紹MyBatis批量刪除語句的使用方法,並附上具體的程式碼範例。使用場景:在資料庫中刪除大量資料時,逐條執行刪除語句效率低。此時,可以使用MyBatis的批次刪除功能

MyBatis快取機制詳解:一文讀懂快取儲存原理引言在使用MyBatis進行資料庫存取時,快取是一個非常重要的機制,能夠有效減少對資料庫的訪問,提高系統效能。本文將詳細介紹MyBatis的快取機制,包括快取的分類、儲存原理和具體的程式碼範例。一、快取的分類MyBatis的快取主要分為一級快取和二級快取兩種。一級緩存一級緩存是SqlSession級別的緩存,當在

iBatis和MyBatis是兩個主流的ORM(Object-RelationalMapping)框架,它們在設計和使用上有著許多相似之處,也存在一些細微的差別。本文將詳細比較iBatis和MyBatis的異同,並透過具體的程式碼範例來說明它們的特點。一、iBatis與MyBatis的歷史與背景iBatis是ApacheSoftwareFoundat

MyBatisGenerator是MyBatis官方提供的程式碼產生工具,可以幫助開發人員快速產生符合資料庫表結構的JavaBean、Mapper介面以及XML映射檔。在使用MyBatisGenerator進行程式碼產生的過程中,配置參數的設定是至關重要的。本文將從配置參數的角度出發,深入探討MyBatisGenerator的
