springboot入門(三)-- springboot集成mybatis及mybatis generator工具使用


前言

mybatis是一個半自動化的orm框架,所謂半自動化就是mybaitis只支持數據庫查出的數據映射到pojo類上,而實體到數據庫的映射需要自己編寫sql語句實現,相較於hibernate這種完全自動化的框架我更喜歡mybatis,mybatis非常靈活,可以隨心所欲的編寫自己的sql語句來實現復雜的數據庫操作,還會有一種暢酣淋漓的編寫sql語句的瀟灑感,但是以前的mybaits需要一大堆的配置文件,以及各種mapper和dao和實體的關聯,導致使用mybatis還是不夠簡潔,后來mybatis也發現了這個弊端,開發了mybatis generator工具來自動化生成實體類、mapper配置文件、dao層代碼來減輕開發工作量,在后期也是實現了拋棄mapper配置文件基於注解的開發模式,直到現在,mybatis看spring boot這么火熱,也開發了一套基於spring boot的模式:mybatis-spring-boot-starter。
spring boot簡約輕巧的風格正在逐漸被越來越多的廠商及開發者所認可,包括阿里的開源RPC框架dubbo也准備開發一套對spring boot應用的支持(dubbo-spring-boot-starter啟動配置模塊)

正文

springboot與mybatis集成

首先還是從http://start.spring.io/ 上初始化一個項目下來,然后在pom.xml文件中加入mybatis啟動項(由於mybatis-spring-boot-starter依賴了spring-boot-starter,所以可以不用再添加spring-boot-starter了)以及mysql及web依賴

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

在application.properties中配置數據源及mybatis配置:

spring.application.name=spring-boot-config
server.port=8080
server.context-path=/ #mybatis.config-location=classpath:mybatis-config.xml
#mybatis mapper文件的位置
mybatis.mapper-locations=classpath*:mapper/**/*.xml
#掃描pojo類的位置,在此處指明掃描實體類的包,在mapper中就可以不用寫pojo類的全路徑名了
mybatis.type-aliases-package=com.cuit
jdbc.type=mysql spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

可以通過mybatis.config-location屬性來指定mybatis的配置文件的位置,簡單起見這里使用默認配置就不用指定了,接下來分別在數據庫中創建user表,並插入一些數據
這里寫圖片描述
分別創建pojo類和dao接口對應mapper文件

public class User{
private String id;
private String name;
private String sex;
private int age; } @Mapper//加上該注解才能使用@MapperScan掃描到
public interface UserDao {
User getUserById(@Param("id") int id);
int updateUser(@Param("user") User user);
int insertUser(@Param("user") User user);
int deleteUserById(@Param("id") int id);
}

對應的mapper文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.cuit.springboot.dao.UserDao">
<select id="getUserById" resultType="User">
SELECT
ID as id,
NAME as name,
SEX as sex,
AGE as age
FROM user
WHERE ID = #{id}
</select>
<update id="updateUser">
UPDATE user
SET NAME = #{user.name},
SEX = #{user.sex},
AGE = #{user.age}
WHERE ID = #{user.id}
</update> <insert id="insertUser">
INSERT INTO
user(id, name, sex, age)
VALUES (
#{user.id},
#{user.name},
#{user.sex},
#{user.age}
)
</insert>
<delete id="deleteUserById">
DELETE user WHERE ID = #{id}
</delete>
</mapper>

在啟動類上加上@MapperScan注解,掃描指定包下的dao類:

@ComponentScan("com.cuit")
@MapperScan("com.cuit")
public class SpringBootApplicationStarter {
...
}

最后寫個Controller方法用於測試:

@RestController
public class HelloController {
@Autowired
private UserDao userDao;
@RequestMapping("/hello")
public User hello(){
User user = userDao.getUserById(1);
System.out.println(user); return user;
}
}

在瀏覽器中輸入http://localhost:8080/hello 可以看到已經查到數據了,sprigboot與mybatis簡單集成就完成了。

使用注解方式

當我們需要一個很簡單的DML功能時,如果去創建mapper文件並編寫一堆語句的時候也許會顯得很麻煩,這個時候就可以通過注解的方式簡化配置,新建一個UserAnnotationDao通過注解的方式來實現增刪改查:

@Mapper
public interface UserAnnotationDao {

@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "sex", column = "sex"),
@Result(property = "age", column = "age")
})
User getUserById(int id);

@Select("SELECT * FROM user")
@Results({ @Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "sex", column = "sex"),
@Result(property = "age", column = "age")
}) List<User> queryAll();

@Update("UPDATE user SET NAME = #{user.name}, SEX = #{user.sex}, AGE = #{user.age} WHERE ID = #{user.id}")
int updateUser(User user);

@Insert("INSERT INTO user(id, name, sex, age) VALUES (#{user.id}, #{user.name}, #{user.sex}, #{user.age})")
int insertUser(User user);

@Delete("DELETE user WHERE ID = #{id}")
int deleteUserById(int id);

}

使用注解自后就不需要mapper文件了,分別測試這幾個方法均能正確執行,使用注解和使用xml的方式都差不多,通常情況下,如果沒有復雜的連接查詢,我們可以使用注解的方式,當設計到復雜的sql還是使用xml的方式更好掌控一些,所以通常情況下兩種方式都會使用,根據sql的復雜程度選擇不同的方式來提高開發效率。

mybatis generator工具的使用

在前言中說到,mybatis也發現了我們需要重復的去創建pojo類、mapper文件以及dao類並且需要配置它們之間的依賴關系可能會很麻煩,所以mybtis提供了一個mybatis generator工具來幫我們自動創建pojo類、mapper文件以及dao類並且會幫我們配置好它們的依賴關系,而我們只需要關系我們的業務邏輯直接使用就行了。
要使用mybatis generator工具需要在pom.xml文件中添加一個generator的maven工具:

 <build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- generator 工具配置文件的位置 -->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</build>

上面指定了mybatis generator工具配置文件的位置,在這個位置創建一個xml文件,並做如下配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<!-- 配置生成器 -->
<generatorConfiguration>
<!--執行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
<!-- 引入配置文件 -->
<properties resource="mybatis-generator/mybatisGeneratorinit.properties"/>
<!--classPathEntry:數據庫的JDBC驅動,換成你自己的驅動位置 可選 -->
<!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar" /> -->
<!-- 一個數據庫一個context -->
<!--defaultModelType="flat" 大數據字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自動識別數據庫關鍵字,默認false,如果設置為true,根據SqlReservedWords中定義的關鍵字列表;
一般保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋 -->

<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的編碼 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認是`反引號; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<!-- 格式化java代碼 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代碼 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 注釋 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消注釋 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注釋代時間戳-->
</commentGenerator>
<!-- jdbc連接 -->
<jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
<!-- 類型轉換 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成實體類地址 -->
<javaModelGenerator targetPackage="com.cuit.springboot.gentry" targetProject="${project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/> </javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mappers" targetProject="${resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml對應client,也就是接口dao -->
<javaClientGenerator targetPackage="com.cuit.springboot.gdao" targetProject="${project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table可以有多個,每個數據庫中的表都可以寫一個table,tableName表示要匹配的數據庫表,也可以在tableName屬性中通過使用%通配符來匹配所有數據庫表,只有匹配的表才會自動生成文件 --> <table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 數據庫表主鍵 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
</context>
</generatorConfiguration>

在同目錄下創建mybatisGeneratorinit.properties文件:

#Mybatis Generator configuration
#dao類和實體類的位置
project =src/main/java
#mapper文件的位置
resources=src/main/resources
#根據數據庫中的表生成對應的pojo類、dao、mapper
jdbc_driver =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/demo
jdbc_user=root
jdbc_password=123456

到此,整個配置就完成了,既然該工具的作用是將數據庫中的表生成對應的實體、dao類和mapper文件,那么首先需要建立數據庫表,當數據庫表建立好后在pom.xml文件所在的目錄執行如下命令:

mvn mybatis-generator:generate

然后就可以看到在指定目錄下已經生成了對應的文件,關於mybatis generator的更多詳細的配置可以參考這篇文章:Mybatis Generator最完整配置詳解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM