SpringBoot教程(4):整合MyBatis逆向工程

1.新建maven工程,pom.xml:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.liit</groupId>
  <artifactId>springboot_mybais02</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springboot_mybais02 Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <!--    父节点    -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--
    指定编码格式和jdk版本
    -->
    <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>
      <!--
        spring-boot-starter-web: MVC,AOP的依赖包....
     -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <!--
      加入lombok,注解生成Getter、Setter
      -->
      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
      </dependency>
      <!--     mybatis generator插件      -->
      <dependency>
          <groupId>tk.mybatis</groupId>
          <artifactId>mapper-spring-boot-starter</artifactId>
          <version>1.1.1</version>
      </dependency>
      <!--      添加fastjson 依赖包.解析json数据       -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.15</version>
      </dependency>
      <!-- 热部署,spring boot devtools 依赖包.底下还要构建节点 -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-devtools</artifactId>
          <optional>true</optional>
          <scope>true</scope>
      </dependency>
      <!--      mysql 数据库驱动.       -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
      </dependency>
      <!--      spring-boot mybatis依赖:      -->
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>1.3.1</version>
      </dependency>
      <!--分页插件     -->
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper</artifactId>
          <version>4.1.0</version>
      </dependency>
      <!-- servlet 依赖. -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
      </dependency>
      <!-- JSTL-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
      </dependency>
      <!-- tomcat 的支持.-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
      </dependency>
      <dependency>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-jasper</artifactId>
      </dependency>

  </dependencies>
    <!-- 构建节点. -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <!--           mybatis-gnerator插件            -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.6</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.4.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

2.resources中添加配置文件:

application.properties:

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/springboot_test
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10


########################################################
### Java Persistence Api --  Spring jpa\u7684\u914d\u7f6e\u4fe1\u606f.
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

#########################################################
###解决乱码问题
########################################################
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

#########################################################
###定义返回jsp
########################################################
# 返回jsp前缀
spring.mvc.view.prefix=/WEB-INF/jsp/
# 返回jsp后缀
spring.mvc.view.suffix=.jsp

#########################################################
###serivice设置(Tomcat)
########################################################
#springboot默认端口号8080,更改:
#server.port=8081
#springboot默认访问地址是:http://ip:port/spring_boot,更改:
#server.context-path=/springboot
#server.address= # bind to a specific NIC
#server.session-timeout= # session timeout in seconds
#the context path, defaults to '/'
#server.servlet-path= # the servlet path, defaults to '/'
#server.tomcat.access-log-pattern= # log pattern of the access log
#server.tomcat.access-log-enabled=false # is access logging enabled
#server.tomcat.protocol-header=x-forwarded-proto # ssl forward headers
#server.tomcat.remote-ip-header=x-forwarded-for
#server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp)
#server.tomcat.background-processor-delay=30; # in seconds
#server.tomcat.max-threads = 0 # number of threads in protocol handler
#server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding

#########################################################
###THYMELEAF (ThymeleafAutoConfiguration)
########################################################
#spring.thymeleaf.prefix=classpath:/tem/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
# ;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html
# set to false for hot refresh
#spring.thymeleaf.cache=false

########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
#spring.freemarker.allow-request-override=false
#spring.freemarker.cache=false
#spring.freemarker.check-template-location=true
#spring.freemarker.charset=UTF-8
#spring.freemarker.content-type=text/html
#spring.freemarker.expose-request-attributes=false
#spring.freemarker.expose-session-attributes=false
#spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=classpath:/tem/
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/tem/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

########################################################
###mybatis generator插件:
########################################################mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
mapper.Mapper = tk.mybatis.mapper.common.Mapper
mybatis.type-aliases-package=com.liit.pojo
#分模块放
mybatis.mapper-locations=classpath:mapper/*.xml
mapper.mappers=com.liit.basemapper.BaseMapper
mapper.not-empty=false
mapper.identity=MYSQL

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="baseset"  targetRuntime="MyBatis3Simple" defaultModelType="flat">

        <!-- 根据Mapper生成实体类,xml文件 -->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.liit.basemapper.BaseMapper"/>
        </plugin>

        <!-- 连接字符串 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/springboot_test"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!-- 指定生成“entity实体类、mybatis映射xml文件、mapper接口”的具体位置 -->
        <javaModelGenerator targetPackage="com.liit.pojo" targetProject="src/main/java" >
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapperXML" targetProject="src/main/resources" >
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="com.liit.mapping" targetProject="src/main/java"   type="XMLMAPPER" >
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


        <!-- 具体要生成的表,如果有多个表,复制这一段,改下表名即可 -->
        <table   tableName="demo1"  domainObjectName="Demo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

logback.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2010-2011 The myBatis Team
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<configuration>
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="C:/Users/progr/Desktop/SpringBootLogTest" ></property>
    <!-- 彩色日志 -->
    <!-- 彩色日志依赖的渲染类 -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <!-- 彩色日志格式 -->
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
    <!-- Console 输出设置 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- 不用彩色控制台输出 -->
    <!--<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">-->
    <!--<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">-->
    <!--&lt;!&ndash;格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符&ndash;&gt;-->
    <!--<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
    <!--</encoder>-->
    <!--</appender>-->
    <!-- 按照每天生成日志文件 -->
    <appender name="DAYINFO"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/TestSpringBoot_info.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <appender name="DAYERROR"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/TestSpringBoot_error.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>error</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- 日志输出级别 -->

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="DAYERROR" />
        <appender-ref ref="DAYINFO" />
    </root>
</configuration>

3.点击run。

保存以后运行:

4. 这样就自动生成了xml,mapper,entity。但是mapper只是个半成品,还需要自定义sql语句。

Mapper:

package com.liit.mapping;
import com.liit.pojo.Demo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;
@Mapper
public interface DemoMapper{
    @Select("select *from Demo where name = #{name}")
    public List<Demo> likeName(String name);

    @Select("select * from Demo where id = #{id}")
    public Demo getById(long id);

    @Select("select name from Demo where id = #{id}")
    public String getNameById(long id);

    @Insert("insert Demo(name) values (#{name}) ")
    @Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
    public void insert(Demo demo);

}

service:

package com.liit.service;
import com.liit.mapping.DemoMapper;
import com.liit.pojo.Demo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DemoService {
    @Resource
    private DemoMapper demoMapper;

    public List<Demo> likeName(String name){
        return demoMapper.likeName(name);
    }
    public void insert(Demo demo){
        demoMapper.insert(demo);
    }
}

Controller:

package com.liit.controller;
import com.liit.pojo.Demo;
import com.liit.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class DemoController {
    @Resource
    private DemoService demoService;
    @RequestMapping("demo")
    public String index(){
        Demo demo=new Demo();
        demo.setName("我aini");
        demoService.insert(demo);
        int id =demo.getId();
        System.out.print(id);
        return "demo";
    }


    @RequestMapping("/likeName")
    public @ResponseBody List<Demo> likeName(String name){
        return demoService.likeName(name);
        //http://127.0.0.1:8080/likeName?name=我aini
    }

}

5. 项目结构:

源码:

github

https://github.com/southwind9801/springboot_mybais03.git

原文发布于微信公众号 - Java大联盟(javaunion)

原文发表时间:2018-06-14

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Java3y

SpringMVC【开发Controller】详解

前言 本文主要是讲解在Controller中的开发,主要的知识点有如下: 编码过滤器 使用注解开发 注解@RequestMapping详解 业务方法接收参数 字...

2888
来自专栏Java 技术分享

SpringMVC(一)

1012
来自专栏日常分享

抛开深层次底层,快速入门SpringMVC

SpringMVC主要有三个核心部分组成,DispatcherServlet、Controller、ViewResolver。      Dispatche...

773
来自专栏技术与生活

Spring Boot的过滤器

其中1代表是微服务启动类,2代表在启动类下面构建一个包,再在堡垒新建一个过滤器类,并且实现 Filter 接口

1411
来自专栏青枫的专栏

day33_Spring学习回顾_01

1、导入jar包:4 + 1 --> beans/core/context/expression + commons-logging

552
来自专栏陈本布衣

Spring基础篇——通过Java注解和XML配置装配bean

自动化装配的确有很大的便利性,但是却并不能适用在所有的应用场景,比如需要装配的组件类不是由自己的应用程序维护,而是引用了第三方的类库,这个时候自动装配便无法实...

4046
来自专栏Linyb极客之路

Spring Cloud开发注意事项

如果provider中需要引入其他feign client的接口,需在 provider的启动类添加注解 @EnableFeignClients(basePac...

1213
来自专栏游戏杂谈

fabrication的拦截器Interceptors简介

Interceptors(拦截器),主要目的是为了改变PureMVC的消息通知在到达Commands和Mediators的正常执行顺序。 在拦截器里可以:

712
来自专栏Java 技术分享

SpringMVC(一)

1473
来自专栏学海无涯

Java Web之SpringMVC 进行参数绑定

学习方法 当需要学习一个新的MVC框架需要从以下方面入手: 1、环境搭建(能输出Hello Word) 2、如何传递参数到Controller,Contr...

33611

扫码关注云+社区