springboot-springmvc-mybatis整合

真的超级简单。。。。mybatis只需要两行代码配置文件就ok了,对了,有个坑,mybatis的版本问题,高版本的需要在接口的dao层需要加上@mapper注解,不然注入失败。

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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.qytxgroupId>
    <artifactId>mama-bikeartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>mama-bikename>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.10.RELEASEversion>
        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        
        <druid.version>1.0.9druid.version>
        
        <jdbc.version>5.1.30jdbc.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.1.1version>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>${druid.version}version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${jdbc.version}version>
        dependency>


        
        <dependency>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-coreartifactId>
            <version>1.3.2version>
            <scope>testscope>
        dependency>


        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>

    dependencies>

    <build>

        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
        resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                   <fork>truefork>
                configuration>
            plugin>

            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.2version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xmlconfigurationFile>
                    <verbose>trueverbose>
                    <overwrite>trueoverwrite>
                configuration>
            plugin>
        plugins>
    build>


project>

application.yml

server:
  port: 8080
spring:
    datasource:
        name: test
        url: jdbc:mysql://localhost:3306/mama-bike?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
        username: root
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

mybatis:
  mapper-locations: classpath:com/coder520/mamabike/**/**.xml
  type-aliases-package: classpath:com.coder520.mamabike.**.entity
logging:
  config: classpath:logback.xml

logback.xml

坑超级多,特别是jar、包问题,根本不需要引其他jar包,因为boot里面集成的有。。。。麻痹,浪费我两个小时!!!!!

还有logger日志类引入问题,idea麻痹不提示,卧槽,说好的智能提示呢,只有等我把全部的写完才提示不报错,擦
别引错类!!!!!

import org.slf4j.LoggerFactory;
Logger logger=LoggerFactory.getLogger(UserController.class);
logger.error("出错了------");

<configuration>
    
    <property name="LOG_HOME" value="logs/mamabike/" />

    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{H:mm} %-5level [%logger{16}] %msg%npattern>
        encoder>
    appender>

    <appender name="normalLog"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <FileNamePattern>${LOG_HOME}/web.normal.%d{yyyy-MM-dd}.log
            FileNamePattern>
            
            <MaxHistory>30MaxHistory>
        rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            
            <maxFileSize>10MBmaxFileSize>
        triggeringPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{16} - %msg%n
            pattern>
        layout>

        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>DENYonMatch>
            <onMismatch>ACCEPTonMismatch>
        filter>
    appender>
    <appender name="errorLog"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${LOG_HOME}/web.error.%d{yyyy-MM-dd}.log
            FileNamePattern>
            <MaxHistory>30MaxHistory>
        rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>10MBmaxFileSize>
        triggeringPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{16} - %msg%n
            pattern>
        layout>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERRORlevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    
    <logger name="com.coder520.mamabike" level="debug" >
        <appender-ref ref="normalLog" />
        <appender-ref ref="errorLog" />
    logger>

    
    <root level="info">
        <appender-ref ref="Console" />
    root>
configuration>

替换springboot内置的json解析包,因为springboot内置的是jackson.jar 不好使,所以用阿里巴巴的fastjson。 他们两个最大的区别就是一个类,如果某个字段为null,fastjson不给你返回,jsckson给你返回这个字段,值为null。

一般这样替换
在主main函数中写一个方法,注解@Bean 然后spring就会扫描到。然后就会把这个返回的类给替换掉!!!!

package com.coder520.mamabike;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter;

@SpringBootApplication
@ComponentScan(basePackages={"com.coder520.mamabike"})
public class MamaBikeApplication {

    public static void main(String[] args) {
        SpringApplication.run(MamaBikeApplication.class, args);
    }
    @Bean
    public HttpMessageConverters fastJsonMessageConverter(){
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        HttpMessageConverter httpMessageConverters=fastJsonHttpMessageConverter;
        return new HttpMessageConverters(httpMessageConverters);
    }
}

还有一个提高效率的功能,省去实体类的getset方法和每个类需要new一个日志工厂,全部注解就可以

需要加上一个依赖和idea需要下载一个插件Lombok插件。@data注解用在实体类上,@slf4j用在类上

 
        
            org.projectlombok
            lombok
            1.16.6
        



package com.coder520.mamabike.user.controller;

import ch.qos.logback.classic.selector.servlet.LoggerContextFilter;
import com.coder520.mamabike.user.dao.UserMapper;
import com.coder520.mamabike.user.entity.User;
import com.coder520.mamabike.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Administrator on 2018/2/14.
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {


    @Autowired
    UserService userService;
    @RequestMapping("/list")
    public User hello(){
        User user = userService.getUser(10L);
        try {
            user.getMobile().lastIndexOf(1);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("出错了------");
        }
        return user;
    }
}

你可能感兴趣的:(springboot)