SpringBoot學習--04SpringBoot整合Mybatis(上)(配置mybatis generator)

 

陸陸續續又忙了幾天,繼續寫。java

本篇仿照着優秀的文章的書寫,加上本身的理解和踩過的坑,原文地址:https://www.jianshu.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixinmysql

環境/版本一覽:

  • 開發工具:eclipse
  • springboot: 2.0.1.RELEASE
  • jdk:1.8.0_40
  • maven:3.3.9

額外功能:

  • mybatis generator 自動生成代碼插件

開始搭建:

一.建立項目:

一、一樣如上文,建立SpringBoot項目(默認爲最新版),web

二、填寫項目的基礎信息,spring

三、選擇基礎的項目依賴包,能夠之後手動添加,sql

四、選擇finish,等待依賴包加載完成。數據庫

這是生成pom.xml文件apache

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>com.luozhen</groupId>
 7     <artifactId>StudyForSpringBoot</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>StudyForSpringBoot</name>
12     <description>There are two kinds of life, one is burning, the other is rotten.</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>2.0.1.RELEASE</version>
18         <relativePath/> <!-- lookup parent from repository -->
19     </parent>
20 
21     <properties>
22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24         <java.version>1.8</java.version>
25     </properties>
26 
27     <dependencies>
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-starter-web</artifactId>
31         </dependency>
32         <dependency>
33             <groupId>org.mybatis.spring.boot</groupId>
34             <artifactId>mybatis-spring-boot-starter</artifactId>
35             <version>1.3.2</version>
36         </dependency>
37 
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-devtools</artifactId>
41             <scope>runtime</scope>
42         </dependency>
43         <dependency>
44             <groupId>mysql</groupId>
45             <artifactId>mysql-connector-java</artifactId>
46             <scope>runtime</scope>
47         </dependency>
48         <dependency>
49             <groupId>org.springframework.boot</groupId>
50             <artifactId>spring-boot-starter-test</artifactId>
51             <scope>test</scope>
52         </dependency>
53     </dependencies>
54 
55     <build>
56         <plugins>
57             <plugin>
58                 <groupId>org.springframework.boot</groupId>
59                 <artifactId>spring-boot-maven-plugin</artifactId>
60             </plugin>
61         </plugins>
62     </build>
63 
64 
65 </project>

這是生成的文件目錄,其中的配置文件application.properties能夠根據本身的習慣選擇,使用properties或者yml文件,本項目使用的是yml配置文件,因此把本來application.properties刪除,建立一個application.yml文件springboot

更改後:(能夠直接 rename後綴名爲yml)mybatis

二.配置mybatis及自動生成代碼generate

mybatis配置有兩種,一種是註解版,在代碼中配置;另外一種是xml版,搭配generate,能夠靈活的動態生成SQL,很方便的調整SQL.架構

此處咱們講解的是xml版,搭配generate使用.

1.儘管咱們在前面建立項目的時候依賴了mybatis依賴包,可是咱們仍是要確認下.若是前面沒有勾選,咱們也能夠手動導入mybatis依賴包,在<dependencies>標籤中寫入一下代碼導入依賴,

1         <dependency>
2             <groupId>org.mybatis.spring.boot</groupId>
3             <artifactId>mybatis-spring-boot-starter</artifactId>
4             <version>1.3.2</version>
5         </dependency>

2.接下來就是application.yml配置文件中添加相關的配置.

 1 #端口號
 2 server:
 3   port: 55555
 4 
 5 #datasource,數據鏈接
 6 spring:
 7   datasource:
 8     driver-class-name: com.mysql.jdbc.Driver
 9     # 基本屬性
10     url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
11     username: root
12     password: 123456
13 
14 #mybatis
15 mybatis:
16   type-aliases-package: com.luozhen.entity #實體類映射文件包
17   mapper-locations: classpath:mybatis/mappers/*.xml #生成的sql語句

以上的就是配置文件的基礎配置,後續可加入詳細的內容,同時須要注意#mybatis後面的配置須要對應的文件包,如下爲個人文件包,

不少文章上都寫了須要mybatis-config.xml文件,可是你會發現其中的內容會和application.yml的重複,配置爲數據庫的鏈接配置.SpringBoot會自動加載,spring.datasource.*相關配置,數據源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中,對了你一切都不用管了,直接拿起來使用就好了。

4.到這裏mybatis的配置就完成了,接下就是generate的配置.一樣,也是須要在pom.xml中導入依賴包,在<build><plugins></plugins></build>中添加依賴,

 1 <!-- generator自動生成代碼依賴包 -->
 2       <plugin>
 3         <groupId>org.mybatis.generator</groupId>
 4         <artifactId>mybatis-generator-maven-plugin</artifactId>
 5         <version>1.3.5</version>
 6         <configuration>
 7           <!-- 配置generatorConfig的位置,注意:若不配置generatorConfig的位置,會默認位置爲src/main/resources下。 -->
 8           <configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
 9           <verbose>true</verbose>
10           <overwrite>true</overwrite>
11         </configuration>
12         <executions>
13           <execution>
14             <id>Generate MyBatis Files</id>
15             <goals>
16               <goal>generate</goal>
17             </goals>
18             <phase>generate</phase>
19             <configuration>
20               <verbose>true</verbose>
21               <overwrite>true</overwrite>
22             </configuration>
23           </execution>
24         </executions>
25         <dependencies>
26           <dependency>
27             <groupId>MySQL</groupId>
28             <artifactId>mysql-connector-Java</artifactId>
29             <version>5.1.46</version>
30           </dependency>
31           <dependency>
32             <groupId>org.mybatis.generator</groupId>
33             <artifactId>mybatis-generator-core</artifactId>
34             <version>1.3.6</version>
35           </dependency>
36           <dependency>
37             <groupId>org.mybatis</groupId>
38             <artifactId>mybatis</artifactId>
39             <version>3.4.6</version>
40           </dependency>
41         </dependencies>
42       </plugin>

5.配置generatorConfig.xml,內容,

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 
 3     <!DOCTYPE generatorConfiguration 
 4       PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 5       "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 6 
 7 <generatorConfiguration>
 8   <context id="mysqlTables" targetRuntime="MyBatis3">
 9     <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
10     <commentGenerator>
11       <property name="suppressDate" value="false" />
12       <property name="suppressAllComments" value="true" />
13     </commentGenerator>
14     <!-- 數據庫連接URL,用戶名、密碼 -->
15     <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false" userId="root" password="123456">
16     </jdbcConnection>
17 
18     <javaTypeResolver>
19       <property name="forceBigDecimals" value="false" />
20     </javaTypeResolver>
21 
22     <!-- 生成model模型,對應的包,存放位置能夠指定具體的路徑,如/ProjectName/src,也可使用MAVEN來自動生成 -->
23     <javaModelGenerator targetPackage="com.luozhen.entity" targetProject="src/main/java">
24       <property name="enableSubPackages" value="true" />
25       <property name="trimStrings" value="true" />
26     </javaModelGenerator>
27 
28     <!--對應的xml mapper文件 -->
29     <sqlMapGenerator targetPackage="mybatis/mappers" targetProject="src/main/resources">
30       <property name="enableSubPackages" value="true" />
31     </sqlMapGenerator>
32 
33     <!-- 對應的dao接口 -->
34     <javaClientGenerator type="XMLMAPPER" targetPackage="com.luozhen.daos" targetProject="src/main/java">
35       <property name="enableSubPackages" value="true" />
36     </javaClientGenerator>
37 
38 
39     <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名(不生成Example(幫助類)類) -->
40     <table tableName="sys_department" domainObjectName="SysDepartment" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
41     </table>
42 
43   </context>
44 
45 </generatorConfiguration>

具體的參考配置能夠查看:

 

https://www.jianshu.com/p/e09d2370b796 Mybatis Generator最完整配置詳解

 

6.最後配置generator生成,F5刷新

 項目 右鍵==>run as ==> maven bulid ==>彈出對話框 ==>在goals中輸入mybatis-enerator:generate 或者 點擊select --》選擇你的mybatis插件 --》apply --》run,結果以下

 

搭建完成後的目錄及文件:

目錄:

個人數據庫表結構:

生成的實體,SysDepartment.java:

 1 package com.luozhen.entity;
 2 
 3 import java.util.Date;
 4 
 5 import org.springframework.format.annotation.DateTimeFormat;
 6 
 7 import com.fasterxml.jackson.annotation.JsonFormat;
 8 
 9 public class SysDepartment {
10     private String id;
11 
12     private String name;
13 
14     private Date createdate;
15 
16     private String parentId;
17 
18     public String getId() {
19         return id;
20     }
21 
22     public void setId(String id) {
23         this.id = id == null ? null : id.trim();
24     }
25 
26     public String getName() {
27         return name;
28     }
29 
30     public void setName(String name) {
31         this.name = name == null ? null : name.trim();
32     }
33 
34     public Date getCreatedate() {
35         return createdate;
36     }
37 
38     public void setCreatedate(Date createdate) {
39         this.createdate = createdate;
40     }
41 
42     public String getParentId() {
43         return parentId;
44     }
45 
46     public void setParentId(String parentId) {
47         this.parentId = parentId == null ? null : parentId.trim();
48     }
49 }

生成的mapper.xml,在resources/mybatis/mappers下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.luozhen.daos.SysDepartmentMapper">
 4   <resultMap id="BaseResultMap" type="com.luozhen.entity.SysDepartment">
 5     <id column="ID" jdbcType="VARCHAR" property="id" />
 6     <result column="NAME" jdbcType="VARCHAR" property="name" />
 7     <result column="CREATEDATE" jdbcType="TIMESTAMP" property="createdate" />
 8     <result column="PARENT_ID" jdbcType="VARCHAR" property="parentId" />
 9   </resultMap>
10   <sql id="Base_Column_List">
11     ID, NAME, CREATEDATE, PARENT_ID
12   </sql>
13   <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
14     select 
15     <include refid="Base_Column_List" />
16     from sys_department
17     where ID = #{id,jdbcType=VARCHAR}
18   </select>
19   <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
20     delete from sys_department
21     where ID = #{id,jdbcType=VARCHAR}
22   </delete>
23   <insert id="insert" parameterType="com.luozhen.entity.SysDepartment">
24     insert into sys_department (ID, NAME, CREATEDATE, PARENT_ID)
25     values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP}, 
26       #{parentId,jdbcType=VARCHAR})
27   </insert>
28   <insert id="insertSelective" parameterType="com.luozhen.entity.SysDepartment">
29     insert into sys_department
30     <trim prefix="(" suffix=")" suffixOverrides=",">
31       <if test="id != null">
32         ID,
33       </if>
34       <if test="name != null">
35         NAME,
36       </if>
37       <if test="createdate != null">
38         CREATEDATE,
39       </if>
40       <if test="parentId != null">
41         PARENT_ID,
42       </if>
43     </trim>
44     <trim prefix="values (" suffix=")" suffixOverrides=",">
45       <if test="id != null">
46         #{id,jdbcType=VARCHAR},
47       </if>
48       <if test="name != null">
49         #{name,jdbcType=VARCHAR},
50       </if>
51       <if test="createdate != null">
52         #{createdate,jdbcType=TIMESTAMP},
53       </if>
54       <if test="parentId != null">
55         #{parentId,jdbcType=VARCHAR},
56       </if>
57     </trim>
58   </insert>
59   <update id="updateByPrimaryKeySelective" parameterType="com.luozhen.entity.SysDepartment">
60     update sys_department
61     <set>
62       <if test="name != null">
63         NAME = #{name,jdbcType=VARCHAR},
64       </if>
65       <if test="createdate != null">
66         CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
67       </if>
68       <if test="parentId != null">
69         PARENT_ID = #{parentId,jdbcType=VARCHAR},
70       </if>
71     </set>
72     where ID = #{id,jdbcType=VARCHAR}
73   </update>
74   <update id="updateByPrimaryKey" parameterType="com.luozhen.entity.SysDepartment">
75     update sys_department
76     set NAME = #{name,jdbcType=VARCHAR},
77       CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
78       PARENT_ID = #{parentId,jdbcType=VARCHAR}
79     where ID = #{id,jdbcType=VARCHAR}
80   </update>
81 </mapper>

對應的daos文件,SysDepartmentMapper.java:

 1 package com.luozhen.daos;
 2 
 3 import java.util.List;
 4 
 5 import com.luozhen.entity.SysDepartment;
 6 
 7 public interface SysDepartmentMapper {
 8     int deleteByPrimaryKey(String id);
 9 
10     int insert(SysDepartment record);
11 
12     int insertSelective(SysDepartment record);
13 
14     SysDepartment selectByPrimaryKey(String id);
15 
16     int updateByPrimaryKeySelective(SysDepartment record);
17 
18     int updateByPrimaryKey(SysDepartment record);
19 
20 }

 

使用:

已經完成生成文件,如今咱們要使用生成的文件,使用生成mapper.xml中SQL語句,有兩種方法,一種統一,一種分散,看你的我的習慣.

(1)統一

1.首先在你的啓動類中添加一個註解,註解的目錄爲生成的dao類文件目錄,以下

 1 package com.luozhen;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 @SpringBootApplication //這是重點
 8 @MapperScan("com.luozhen.daos")
 9 public class MySpringBootApplication { 
10     public static void main(String[] args) {
11         SpringApplication.run(MySpringBootApplication.class, args);
12     }
13 }

2.xml文件中 id屬性必須與你dao類文件中方法名相對應,其中有些坑,下篇文章詳解,

(2)分散.在dao類文件上,每一個添加@Mapper註解,其他相同.

剩下的使用步驟就再也不詳解,請參考文章:

https://www.jianshu.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

無非就是SpringMVC的基礎架構,以上如有問題能夠在評論區提出,你們相互學習.

相關文章
相關標籤/搜索