陸陸續(xù)續(xù)又忙了幾天,繼續(xù)寫般哼。
本篇仿照著優(yōu)秀的文章的書寫宛蚓,加上自己的理解和踩過的坑洲押,原文地址:http://www.reibang.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin
環(huán)境/版本一覽:
- 開發(fā)工具:eclipse
- springboot: 2.0.1.RELEASE
- jdk:1.8.0_40
- maven:3.3.9
額外功能:
- mybatis generator 自動生成代碼插件
開始搭建:
一.創(chuàng)建項目:
1、同樣如上文沧竟,創(chuàng)建SpringBoot項目(默認(rèn)為最新版)铸敏,
2、填寫項目的基礎(chǔ)信息悟泵,
3杈笔、選擇基礎(chǔ)的項目依賴包,可以以后手動添加魁袜,
4桩撮、選擇finish,等待依賴包加載完成峰弹。
這是生成pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.luozhen</groupId>
<artifactId>StudyForSpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>StudyForSpringBoot</name>
<description>There are two kinds of life, one is burning, the other is rotten.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
這是生成的文件目錄,其中的配置文件application.properties可以根據(jù)自己的習(xí)慣選擇,使用properties
或者yml
文件店量,本項目使用的是yml配置文件,所以把原本application.properties
刪除鞠呈,創(chuàng)建一個application.yml
文件,也可以直接 rename后綴名為yml
更改后:
二.配置mybatis及自動生成代碼generate
mybatis配置有兩種,一種是注解版,在代碼中配置;另一種是xml版,搭配generate,可以靈活的動態(tài)生成SQL,很方便的調(diào)整SQL.
此處我們講解的是xml版,搭配generate使用.
1.盡管我們在前面創(chuàng)建項目的時候依賴了mybatis依賴包,但是我們還是要確認(rèn)下.如果前面沒有勾選,我們也可以手動導(dǎo)入mybatis依賴包,在<dependencies>標(biāo)簽中寫入一下代碼導(dǎo)入依賴,
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2.接下來就是application.yml配置文件中添加相關(guān)的配置.
#端口號
server:
port: 55555
#datasource
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
# 基本屬性
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
#mybatis
mybatis:
type-aliases-package: com.luozhen.entity
mapper-locations: classpath:mybatis/mappers/*.xml
以上的就是配置文件的基礎(chǔ)配置,后續(xù)可加入詳細(xì)的內(nèi)容,同時需要注意#mybatis后面的配置需要對應(yīng)的文件包,以下為我的文件包,
很多文章上都寫了需要mybatis-config.xml文件,但是你會發(fā)現(xiàn)其中的內(nèi)容會和application.yml的重復(fù),配置為數(shù)據(jù)庫的連接配置.SpringBoot會自動加載,spring.datasource.*相關(guān)配置融师,數(shù)據(jù)源就會自動注入到sqlSessionFactory中,sqlSessionFactory會自動注入到Mapper中蚁吝,對了你一切都不用管了旱爆,直接拿起來使用就行了。
4.到這里mybatis的配置就完成了,接下就是generate的配置.同樣,也是需要在pom.xml中導(dǎo)入依賴包,在<build><plugins></plugins></build>中添加依賴,
<!-- generator自動生成代碼依賴包 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!-- 配置generatorConfig的位置 -->
<configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Files</id>
<goals>
<goal>generate</goal>
</goals>
<phase>generate</phase>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>MySQL</groupId>
<artifactId>mysql-connector-Java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
</plugin>
5.配置generatorConfig.xml,內(nèi)容,
<?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>
<context id="mysqlTables" targetRuntime="MyBatis3">
<!-- 是否去除自動生成的注釋 true:是 : false:否 -->
<commentGenerator>
<property name="suppressDate" value="false" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 數(shù)據(jù)庫鏈接URL窘茁,用戶名怀伦、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false" userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成model模型蜒蕾,對應(yīng)的包介牙,存放位置可以指定具體的路徑,如/ProjectName/src,也可以使用MAVEN來自動生成 -->
<javaModelGenerator targetPackage="com.luozhen.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--對應(yīng)的xml mapper文件 -->
<sqlMapGenerator targetPackage="mybatis/mappers" targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 對應(yīng)的dao接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.luozhen.daos" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成的表 tableName是數(shù)據(jù)庫中的表名或視圖名 domainObjectName是實體類名(不生成Example(幫助類)類) -->
<table tableName="sys_department" domainObjectName="SysDepartment" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
</table>
</context>
</generatorConfiguration>
具體的參考配置可以查看:
http://www.reibang.com/p/e09d2370b796 Mybatis Generator最完整配置詳解
6.最后配置generator生成嚼酝,F(xiàn)5刷新
項目 右鍵==>run as ==> maven bulid ==>彈出對話框 ==>在goals中輸入mybatis-generator:generate 或者 點擊select --》選擇你的mybatis插件 --》apply --》run,結(jié)果如下
搭建完成后的目錄及文件:
目錄:
我的數(shù)據(jù)庫表結(jié)構(gòu):
生成的實體,SysDepartment.java:
package com.luozhen.entity;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
public class SysDepartment {
private String id;
private String name;
private Date createdate;
private String parentId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId == null ? null : parentId.trim();
}
}
生成的mapper.xml,在resources/mybatis/mappers下:
<?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.luozhen.daos.SysDepartmentMapper">
<resultMap id="BaseResultMap" type="com.luozhen.entity.SysDepartment">
<id column="ID" jdbcType="VARCHAR" property="id" />
<result column="NAME" jdbcType="VARCHAR" property="name" />
<result column="CREATEDATE" jdbcType="TIMESTAMP" property="createdate" />
<result column="PARENT_ID" jdbcType="VARCHAR" property="parentId" />
</resultMap>
<sql id="Base_Column_List">
ID, NAME, CREATEDATE, PARENT_ID
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_department
where ID = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from sys_department
where ID = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="com.luozhen.entity.SysDepartment">
insert into sys_department (ID, NAME, CREATEDATE, PARENT_ID)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP},
#{parentId,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.luozhen.entity.SysDepartment">
insert into sys_department
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
ID,
</if>
<if test="name != null">
NAME,
</if>
<if test="createdate != null">
CREATEDATE,
</if>
<if test="parentId != null">
PARENT_ID,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="createdate != null">
#{createdate,jdbcType=TIMESTAMP},
</if>
<if test="parentId != null">
#{parentId,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.luozhen.entity.SysDepartment">
update sys_department
<set>
<if test="name != null">
NAME = #{name,jdbcType=VARCHAR},
</if>
<if test="createdate != null">
CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
</if>
<if test="parentId != null">
PARENT_ID = #{parentId,jdbcType=VARCHAR},
</if>
</set>
where ID = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.luozhen.entity.SysDepartment">
update sys_department
set NAME = #{name,jdbcType=VARCHAR},
CREATEDATE = #{createdate,jdbcType=TIMESTAMP},
PARENT_ID = #{parentId,jdbcType=VARCHAR}
where ID = #{id,jdbcType=VARCHAR}
</update>
對應(yīng)的daos文件,SysDepartmentMapper.java:
package com.luozhen.daos;
import java.util.List;
import com.luozhen.entity.SysDepartment;
public interface SysDepartmentMapper {
int deleteByPrimaryKey(String id);
int insert(SysDepartment record);
int insertSelective(SysDepartment record);
SysDepartment selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(SysDepartment record);
int updateByPrimaryKey(SysDepartment record);
}
使用:
已經(jīng)完成生成文件,現(xiàn)在我們要使用生成的文件,使用生成mapper.xml中SQL語句,有兩種方法,一種統(tǒng)一,一種分散,看你的個人習(xí)慣.
(1)統(tǒng)一
1.首先在你的啟動類中添加一個注解,注解的目錄為生成的dao類文件目錄,如下
package com.luozhen;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.luozhen.daos")
@SpringBootApplication
public class StudyForSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(StudyForSpringBootApplication.class, args);
}
}
2.xml文件中
id屬性必須與你dao類文件中方法名相對應(yīng)
,其中有些坑,下篇文章詳解,
(2)分散.在dao類文件上,每個添加@Mapper注解,其余相同.
剩下的使用步驟就不再詳解,請參考文章:
無非就是SpringMVC的基礎(chǔ)架構(gòu),以上若有問題可以在評論區(qū)提出,大家相互學(xué)習(xí).