`

SpringBoot+Mybatis3+MySQL

阅读更多

说明:该案例的开发环境是idea2017+maven3+SpringBoot1.5.9+Mybatis3+MySQL5.7

最终的案例目录结构如下所示:



 

 

一、添加依赖

在pom.xml文件中,加入springboot依赖、日志文件依赖、tomcat依赖、servlet依赖、jstl依赖、mybatis-spring-boot依赖、jdbc依赖

 

<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">
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.yunlian.springboot</groupId>
  <artifactId>boot-mybatis</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>boot-mybatis</name>
  <url>http://maven.apache.org</url>
  <properties>
    <!-- 需要让整个项目统一字符集编码,就需要设定project.build.sourceEncoding -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--spring boot dependency-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--spring boot log4j dependency-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- Add Log4j2 Dependency -->
    <!--log4j.properties在springboot的高版本会无效,推荐在高版本springboot中使用log4j2-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</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>
    <!-- servlet 依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
    </dependency>
    <!-- 添加 JSTL 支持 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>
    <!-- mybatis-spring-boot dependency-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- mybatis dependency -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.3</version>
    </dependency>
    <!--mysql dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.43</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>boot-mybatis</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

 

 

二、mybatis、db配置

在application.properties文件中,配置如下信息:

 

# 配置jsp文件的位置,默认位置为:src/main/webapp
spring.mvc.view.prefix=/
# 配置jsp文件的后缀
spring.mvc.view.suffix=.jsp

#Spring Boot中的乱码和编码问题
spring.http.encoding.force=true

#除了常见的 http encoding,Spring Boot中还可以控制这些编码
#banner.charset
#spring.freemarker.charset
#server.tomcat.uri-encoding
#spring.mail.default-encoding
#spring.messages.encoding
#spring.thymeleaf.encoding

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/spring-boot
spring.datasource.username = root
spring.datasource.password = root
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

########################################################
### Mybatis 配置
########################################################
mybatis.typeAliasesPackage=com.yunlian.entity
mybatis.mapperLocations=classpath:com/yunlian/dao/*.xml

 

 

三、创建UserDao接口

在dao层创建UserDao接口,并在接口上加上注解Mapper,有了Mapper注解,可以将mybatis完美的融合进springboot中:

package com.yunlian.dao;

import com.yunlian.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserDao {

    User findOne(String id);

    User save(User user);
}

 

四、创建映射文件

在resources目录下面,创建与UserDao.java相同的包目录,在这目录下面创建名为UserDao.xml的映射文件,映射文件的内容如下:

<?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.yunlian.dao.UserDao" >
    <select id="findOne" resultType="user">
        SELECT * FROM user WHERE id=#{id}
    </select>
</mapper>

五、创建业务类

在service包下面创建一个UserService接口,并在service.impl包下面创建UserService接口的实现类UserServiceImpl,并在实现类中注入UserDao的bean,如下所示:

package com.yunlian.service;

import com.yunlian.entity.User;

public interface UserService {

    User getUser();

    void save(User user);
}

 

package com.yunlian.service.impl;

import com.yunlian.dao.UserDao;
import com.yunlian.entity.User;
import com.yunlian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public User getUser() {
       User user =  userDao.findOne("09e7b25c-12f7-43ea-a553-fb34189fce17");
       return user;
    }

    @Override
    public void save(User user) {
        User u = userDao.save(user);
        return;
    }
}

 

六、创建控制层

在controller包下面创建一个UserController类,并在这个类中注入业务类的bean,如下所示:

package com.yunlian.controller;

import com.yunlian.entity.User;
import com.yunlian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/get")
    @ResponseBody
    public User getUser() {
       User user = userService.getUser();
       return user;
    }
}

 

七、配置程序入口类

在入口程序类上加配置注解信息,如下所示:

package com.yunlian.controller;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.yunlian")//包名:扫描这个包下面的加了@Controller注解的类及其子包的加了@Controller注解的类,或者加了Service注解等其他组件注解的类
@MapperScan("com.yunlian.dao")// mapper 接口类扫描包配置
public class SpringBootController {

    public static void main(String[] args) throws Exception {
        //程序启动入口,一般该入口文件不写成控制层
        SpringApplication.run(SpringBootController.class, args);
    }

}

 

八、日志文件

在resources目录下面创建日志文件log4j2-spring.xml,其内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="SYSOUT" target="SYSTEM_OUT">
            <PatternLayout patter="%d [%t] %-5p [%c] - %m%n  "/>
        </Console>

        <!-- name可以自定义,作用是在Loggers中AppenderRef中使用 -->
        <!-- fileName定义输出文件名称(当前文件) -->
        <!-- filePattern定义输出文件名称(文件满足条件后自动截断,生成历史文件) -->
        <RollingFile name="DEBUG_ROLLING_FILE"
                     fileName="~/logs/xxx/logs.logs"
                     filePattern="~/logs/xxx/logs/%d{yyyy-MM-dd}-debugs.log">
            <PatternLayout>
                <Pattern>%d [%t] %-5p [%c] - %m%n  </Pattern>
            </PatternLayout>

            <!-- 文件截断的条件,具体参考文档 -->
            <Policies>
                <TimeBasedTriggeringPolicy interval="24"/>
                <SizeBasedTriggeringPolicy size="250 MB"/>
            </Policies>
        </RollingFile>

        <!-- 同一来源的Appender可以定义多个 -->
        <RollingFile name="ERROR_ROLLING_FILE"
                     fileName="~/logs/xxx/logs/error-logs.logs"
                     filePattern="~/logs/xxx/logs/%d{yyyy-MM-dd}-error.log">
            <!-- 可以通过该参数来设置获取日志的权限 -->
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <Pattern>%d [%t] %-5p [%c] - %m%n  </Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="24"/>
                <SizeBasedTriggeringPolicy size="250 MB"/>
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="SYSOUT"/>
            <AppenderRef ref="DEBUG_ROLLING_FILE"/>
            <AppenderRef ref="ERROR_ROLLING_FILE"/>
        </Root>
        <logger name="org.apache.http" level="ERROR" />
        <!-- Spring -->
        <logger name="org.springframework" level="ERROR" />
        <!-- mybatis loggers -->
        <logger name="com.ibatis" level="INFO" />
        <logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG" />
        <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG" />
        <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG" />
        <!-- sql loggers -->
        <logger name="java.sql.Connection" level="DEBUG"  additivity="true"/>
        <logger name="java.sql.Statement" level="DEBUG" additivity="true" />
        <logger name="java.sql.PreparedStatement" level="=debug,stdout"  additivity="true"/>
        <logger name="java.sql.ResultSet" level="DEBUG"  additivity="true"/>
    </Loggers>
</Configuration>

 

九、运行访问

运行程序入口类的main,运行好后,即可访问   http://localhost:8080/user/get

可以在页面上看到返回的 json 数据

 

 

 

  • 大小: 22.1 KB
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics