構(gòu)建微服務(wù):如何優(yōu)雅的使用mybatis

本文由www.29sl.com轉(zhuǎn)載發(fā)布:這兩天啟動了一個新項(xiàng)目因?yàn)轫?xiàng)目組成員一直都使用的是mybatis,雖然個人比較喜歡jpa這種極簡的模式,但是為了項(xiàng)目保持統(tǒng)一性技術(shù)選型還是定了 mybatis。到網(wǎng)上找了一下關(guān)于spring boot和mybatis組合的相關(guān)資料,各種各樣的形式都有,看的人心累,結(jié)合了mybatis的官方demo和文檔終于找到了最簡的兩種模式,花了一天時間總結(jié)后分享出來。

創(chuàng)新互聯(lián)網(wǎng)站建設(shè)提供從項(xiàng)目策劃、軟件開發(fā),軟件安全維護(hù)、網(wǎng)站優(yōu)化(SEO)、網(wǎng)站分析、效果評估等整套的建站服務(wù),主營業(yè)務(wù)為成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè),成都App定制開發(fā)以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。創(chuàng)新互聯(lián)深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!

orm框架的本質(zhì)是簡化編程中操作數(shù)據(jù)庫的編碼,發(fā)展到現(xiàn)在基本上就剩兩家了,一個是宣稱可以不用寫一句sql的hibernate,一個是可以靈活調(diào)試動態(tài)sql的mybatis。兩者各有特點(diǎn),在企業(yè)級系統(tǒng)開發(fā)中可以根據(jù)需求靈活使用。發(fā)現(xiàn)一個有趣的現(xiàn)象:傳統(tǒng)企業(yè)大都喜歡使用hibernate,互聯(lián)網(wǎng)行業(yè)通常使用mybatis。

hibernate特點(diǎn)就是所有的sql都用Java代碼來生成,不用跳出程序去寫(看)sql,有著編程的完整性,發(fā)展到最頂端就是spring data jpa這種模式了,基本上根據(jù)方法名就可以生成對應(yīng)的sql了,有不太了解的可以看我的上篇文章構(gòu)建微服務(wù):spring data jpa的使用(http://www.ityouknow.com)。

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

現(xiàn)在想想spring boot 就是牛呀,任何東西只要關(guān)聯(lián)到spring boot都是化繁為簡。

mybatis-spring-boot-starter

官方說明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot

其實(shí)就是mybatis看spring boot這么火熱也開發(fā)出一套解決方案來湊湊熱鬧,但這一湊確實(shí)解決了很多問題,使用起來確實(shí)順暢了許多。mybatis-spring-boot-starter主要有兩種解決方案,一種是使用注解解決一切問題,一種是簡化后的老傳統(tǒng)。

當(dāng)然任何模式都需要首先引入mybatis-spring-boot-starter的pom文件,現(xiàn)在最新版本是1.1.1

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.1.1</version></dependency>

好了下來分別介紹兩種開發(fā)模式

無配置文件注解版

就是一切使用注解搞定。

1.添加相關(guān)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 添加相關(guān)配置

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

springboot會自動加載spring.datasource.*相關(guān)配置,數(shù)據(jù)源就會自動注入到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.開發(fā)Mapper

第三步是最關(guān)鍵的一塊,sql生產(chǎn)都在這里

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);

}

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

@Select 是查詢類的注解,所有的查詢均使用這個

@Result 修飾返回的結(jié)果集,關(guān)聯(lián)實(shí)體類屬性和數(shù)據(jù)庫字段一一對應(yīng),如果實(shí)體類屬性和數(shù)據(jù)庫屬性名保持一致,就不需要這個屬性來修飾。

@Insert 插入數(shù)據(jù)庫使用,直接傳入實(shí)體類會自動解析屬性到對應(yīng)的值

@Update 負(fù)責(zé)修改,也可以直接傳入對象

@delete 負(fù)責(zé)刪除

了解更多屬性參考這里http://www.mybatis.org/mybatis-3/zh/java-api.html

注意,使用#符號和$符號的不同:

// 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.使用

上面三步就基本完成了相關(guān)dao層開發(fā),使用的時候當(dāng)作普通的類注入進(jìn)入就可以了。

@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())));

}

}

源碼中controler層有完整的增刪改查,這里就不貼了。源碼在這里spring-boot-mybatis-annotation(https://github.com/ityouknow/spring-boot-starter/tree/master/mybatis-spring-boot/spring-boot-mybatis-annotation)

極簡xml版本

極簡xml版本保持映射文件的老傳統(tǒng),優(yōu)化主要體現(xiàn)在不需要實(shí)現(xiàn)dao的是實(shí)現(xiàn)層,系統(tǒng)會自動根據(jù)方法名在映射文件中找對應(yīng)的sql.

1.配置

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

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

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

指定了mybatis基礎(chǔ)配置文件和實(shí)體類映射文件的地址。

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基礎(chǔ)的配置。

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>

其實(shí)就是把上個版本中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.使用

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

老傳統(tǒng)優(yōu)化版本代碼在這里https://github.com/ityouknow/spring-boot-starter/tree/master/mybatis-spring-boot/spring-boot-mybatis-xml。

如何選擇

兩種模式各有特點(diǎn),注解版適合簡單快速的模式,其實(shí)像現(xiàn)在流行的這種微服務(wù)模式,一個微服務(wù)就會對應(yīng)一個自已的數(shù)據(jù)庫,多表連接查詢的需求會大大的降低,會越來越適合這種模式。

老傳統(tǒng)模式比適合大型項(xiàng)目,可以靈活的動態(tài)生成SQL,方便調(diào)整SQL,也有痛痛快快,洋洋灑灑的寫SQL的感覺。

分享文章:構(gòu)建微服務(wù):如何優(yōu)雅的使用mybatis
轉(zhuǎn)載來源:http://bm7419.com/article18/jcipdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、微信小程序、動態(tài)網(wǎng)站、網(wǎng)站設(shè)計搜索引擎優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)