天天看点

微服务学习(三)Spring Boot整合MyBatis+MySql

idea下工程快速搭建步骤

环境:win10 + idea2018.2 + mysql8.0.15 + mybats

1. 创建工程

微服务学习(三)Spring Boot整合MyBatis+MySql

2. 选择这一项下一步

微服务学习(三)Spring Boot整合MyBatis+MySql

3. 输入自己的包结构和工程名

微服务学习(三)Spring Boot整合MyBatis+MySql

4. 勾选如下图所示

微服务学习(三)Spring Boot整合MyBatis+MySql

5. 继续下一步

微服务学习(三)Spring Boot整合MyBatis+MySql

说明:

这个时候项目已经搭建完成需要根据自己的maven下载相应的jar包结构如下

生成的项目中,resources文件夹下,static文件夹下存放静态文件,比如css、js、html和图片等 。

templates下存放html文件,controller默认访问该文件夹下的html文件。

这个在application.properties配置文件中是可以修改的

微服务学习(三)Spring Boot整合MyBatis+MySql

这个时候项目是不可启动的,启动报下面信息

微服务学习(三)Spring Boot整合MyBatis+MySql

6. 配置application.yml文件(注意yml格式)

server:
port: 8080

spring:
datasource:
name:  king
url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
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/sfc/sso_server/dao/impl/*.xml  #这里是mapper的绝对路径
type-aliases-package: com.sfc.sso_server.entity  #这里是实体类的绝对路径

logging:
level:
com.sfc.sso_server.dao.interfaces: DEBUG

pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
           

7.完整的pom文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sfc</groupId>
<artifactId>sso_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sso_server</name>
<description>Demo project for Spring Boot</description>
<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-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <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>2.0.0</version>
    </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>
    <!-- Druid 数据连接池依赖 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.18</version>
    </dependency>
    <!-- 分页插件 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>4.1.4</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- mybatis generator 自动生成代码插件 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
            <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
            </configuration>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/**</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
           

8. 配置的mysql驱动有个错也能启动

微服务学习(三)Spring Boot整合MyBatis+MySql

-Dspring.output.ansi.enabled=ALWAYS

微服务学习(三)Spring Boot整合MyBatis+MySql

一:Spring Boot基于配置整合MyBatis

1. application.yml文件已经配置完毕在上面

2. pom中添加mybatis自动生成代码插件和mapper文件的配置(mapper不在resouces目录下需要配置)

微服务学习(三)Spring Boot整合MyBatis+MySql

3. generator文件必须创建在resources下面的generator文件夹下面

<?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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包mysql/oracle -->
<classPathEntry  location="D:\Maven\maven-repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>
<context id="DB2Tables"  targetRuntime="MyBatis3">
    <commentGenerator>
        <property name="suppressDate" value="false"/>
        <!-- 是否去除自动生成的注释true:是false:否 -->
        <property name="suppressAllComments" value="false"/>
    </commentGenerator>
    <!-- 数据库连接驱动类、URL、用户名、密码 -->
    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC" userId="root" password="root">
    </jdbcConnection>
    <javaTypeResolver>
        <property name="forceBigDecimals" value="false"/>
    </javaTypeResolver>
    <!-- 生成实体的包名和位置-->
    <javaModelGenerator targetPackage="com.sfc.sso_server.entity" targetProject="src/main/java">
        <property name="enableSubPackages" value="true"/>
        <property name="trimStrings" value="true"/>
    </javaModelGenerator>
    <!-- 生成XML映射文件的包名和位置-->
    <sqlMapGenerator targetPackage="com.sfc.sso_server.dao.impl" targetProject="src/main/java">
        <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>
    <!-- 生成DAO接口的包名和位置-->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.sfc.sso_server.dao.interfaces" targetProject="src/main/java">
        <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>
    <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
    <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
           

4. 然后使用idea下面的maven快捷装置工具双击启动

微服务学习(三)Spring Boot整合MyBatis+MySql

5. 生成完成的工程布局

微服务学习(三)Spring Boot整合MyBatis+MySql

6.启动类修改最终如下

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.sfc.sso_server.dao.interfaces")
public class SsoServerApplication {
	public static void main(String[] args) {
    	SpringApplication.run(SsoServerApplication.class, args);
  }
}
           

开始集成测试

测试一:首先编写一个测试的jdbc

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")
public List<Map<String, Object>> getDbType(){
    String sql = "select * from user";
    List<Map<String, Object>> list =  jdbcTemplate.queryForList(sql);
    System.out.print(list.size());
    return list;
}
}
           

界面输入地址展示如下图,完成测试!!!

微服务学习(三)Spring Boot整合MyBatis+MySql

测试二:测试mabatis集成

1. controller内容:

import com.sfc.sso_server.service.interfaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(@RequestParam String username){
    System.out.println(">>>>>>"+username);
    userService.selectUserList();
    return "index";
}
}
           

2. dao接口

import com.sfc.sso_server.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;

public interface UserMapper {
	int insert(User record);
	int insertSelective(User record);
 	List<User> selectUserList();
}
           

3. mapper.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.sfc.sso_server.dao.interfaces.UserMapper">
<resultMap id="BaseResultMap" type="com.sfc.sso_server.entity.User">
<result column="userName" jdbcType="VARCHAR" property="username" />
<result column="userPassword" jdbcType="VARCHAR" property="userpassword" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>

<select id="selectUserList" resultMap="BaseResultMap">
  select * from user
</select>
<insert id="insert" parameterType="com.sfc.sso_server.entity.User">
insert into user (userName, userPassword, address, 
  age)
values (#{username,jdbcType=VARCHAR}, #	{userpassword,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, 
  #{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.sfc.sso_server.entity.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
  <if test="username != null">
    userName,
  </if>
  <if test="userpassword != null">
    userPassword,
  </if>
  <if test="address != null">
    address,
  </if>
  <if test="age != null">
    age,
  </if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
  <if test="username != null">
    #{username,jdbcType=VARCHAR},
  </if>
  <if test="userpassword != null">
    #{userpassword,jdbcType=VARCHAR},
  </if>
  <if test="address != null">
    #{address,jdbcType=VARCHAR},
  </if>
  <if test="age != null">
    #{age,jdbcType=INTEGER},
  </if>
</trim>
</insert>
</mapper>
           

4.实体类

package com.sfc.sso_server.entity;
public class User {
private String username;
private String userpassword;
private String address;
private Integer age;
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username == null ? null : username.trim();
}
public String getUserpassword() {
    return userpassword;
}
public void setUserpassword(String userpassword) {
    this.userpassword = userpassword == null ? null : userpassword.trim();
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address == null ? null : address.trim();
}
public Integer getAge() {
    return age;
}
public void setAge(Integer age) {
    this.age = age;
}
}
           

5.service接口

public interface UserService {
 public void selectUserList();
}
           

6.service接口实现

import com.sfc.sso_server.dao.interfaces.UserMapper;
import com.sfc.sso_server.entity.User;
import com.sfc.sso_server.service.interfaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void selectUserList() {
    System.out.println(">>>>>开始查询...");
    List<User> list = userMapper.selectUserList();
    System.out.println(">>>>>开始查询结束!"+list.size());
}
}
           

7.界面访问,完成测试!!!

微服务学习(三)Spring Boot整合MyBatis+MySql

看看后台日志打印情况

微服务学习(三)Spring Boot整合MyBatis+MySql

Spring Boot基于配置实现一套整合mabats的程序完成,下面有时间在写一套基于代码管理类的整合。

二:Spring Boot基于管理类方式整合MyBatis

继续阅读