SpringBoot学习--04SpringBoot整合Myba

2018-05-31  本文已影响0人  渊默十三

陆陆续续又忙了几天,继续写。

本篇仿照着优秀的文章的书写,加上自己的理解和踩过的坑,原文地址:https://www.jianshu.com/p/5cd772c07041?utm_campaign=haruki&utm_content=note&utm_medium=reader_share&utm_source=weixin

环境/版本一览:

额外功能:

开始搭建:

一.创建项目:

1、同样如上文,创建SpringBoot项目(默认为最新版),

image

2、填写项目的基础信息,

image

3、选择基础的项目依赖包,可以以后手动添加,

image

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可以根据自己的习惯选择,使用properties或者yml文件,本项目使用的是yml配置文件,所以把原本application.properties删除,创建一个application.yml文件,也可以直接 rename后缀名为yml

image

更改后:

image

二.配置mybatis及自动生成代码generate

mybatis配置有两种,一种是注解版,在代码中配置;另一种是xml版,搭配generate,可以灵活的动态生成SQL,很方便的调整SQL.

此处我们讲解的是xml版,搭配generate使用.

1.尽管我们在前面创建项目的时候依赖了mybatis依赖包,但是我们还是要确认下.如果前面没有勾选,我们也可以手动导入mybatis依赖包,在<dependencies>标签中写入一下代码导入依赖,

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

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

#端口号
server:
  port: 55555

#datasource
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    # 基本属性
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false
    username: root
    password: 123456

#mybatis
mybatis:
  type-aliases-package: com.luozhen.entity
  mapper-locations: classpath:mybatis/mappers/*.xml

以上的就是配置文件的基础配置,后续可加入详细的内容,同时需要注意#mybatis后面的配置需要对应的文件包,以下为我的文件包,

image

很多文章上都写了需要mybatis-config.xml文件,但是你会发现其中的内容会和application.yml的重复,配置为数据库的连接配置.SpringBoot会自动加载,spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

4.到这里mybatis的配置就完成了,接下就是generate的配置.同样,也是需要在pom.xml中导入依赖包,在<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,内容,

<?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>
    <!-- 数据库链接URL,用户名、密码 -->
    <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">
    </jdbcConnection>

    <javaTypeResolver>
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- 生成model模型,对应的包,存放位置可以指定具体的路径,如/ProjectName/src,也可以使用MAVEN来自动生成 -->
    <javaModelGenerator targetPackage="com.luozhen.entity" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!--对应的xml mapper文件 -->
    <sqlMapGenerator targetPackage="mybatis/mappers" targetProject="src/main/resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- 对应的dao接口 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.luozhen.daos" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>


    <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名(不生成Example(帮助类)类) -->
    <table tableName="sys_department" domainObjectName="SysDepartment" enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
    </table>

  </context>

</generatorConfiguration>

具体的参考配置可以查看:

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

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

项目 右键==>run as ==> maven bulid ==>弹出对话框 ==>在goals中输入mybatis-generator:generate 或者 点击select --》选择你的mybatis插件 --》apply --》run,结果如下

image

搭建完成后的目录及文件:

目录:

image

我的数据库表结构:

image

生成的实体,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>

对应的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);
  
}

使用:

已经完成生成文件,现在我们要使用生成的文件,使用生成mapper.xml中SQL语句,有两种方法,一种统一,一种分散,看你的个人习惯.

(1)统一

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文件中

image

id属性必须与你dao类文件中方法名相对应

image

,其中有些坑,下篇文章详解,

(2)分散.在dao类文件上,每个添加@Mapper注解,其余相同.

image.png

剩下的使用步骤就不再详解,请参考文章:

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

无非就是SpringMVC的基础架构,以上若有问题可以在评论区提出,大家相互学习.

上一篇下一篇

猜你喜欢

热点阅读