SpringBoot Mybatis 集成
一个简单的SpringBoot项目,用到了一些自己常用的技术。
数据库连接池为HiKariCP
Mybatis集成了通用Mapper和PageHelper
Lombok
一、用Gradle构建项目,并在IDEA中打开
如下为build.gradle文件内容:
buildscript {
repositories {
mavenLocal()
maven { url 'https://plugins.gradle.org/m2/' } // 用于下载Gradle插件
maven { url 'http://jcenter.bintray.com/' }
maven { url 'http://repo1.maven.org/maven2/' }
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'http://repo.spring.io/milestone' }
maven { url 'http://repo.spring.io/libs-milestone/' }
maven { url 'http://repo.spring.io/release' }
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE' // org.springframework.boot的构建版本控制
classpath 'io.spring.gradle:dependency-management-plugin:1.0.1.RELEASE' // 用于管理jar包之间的依赖问题
}
}
apply plugin: 'java' // java插件,同时也声明是一个java项目
apply plugin: 'idea' // idea插件,可直接让IDEA集成能力
apply plugin: 'org.springframework.boot' // 管理这个组织的jar包插件
apply plugin: 'io.spring.dependency-management' // 管理jar包之间的依赖关系
idea {
module {
inheritOutputDirs = false
outputDir = file("$buildDir/classes/main/") // 在idea中build后输出的class目录
}
}
jar {
baseName = 'springboot'
version = new Date().format("yyyy-MM-dd_HH:mm").toString() // 根据当前时间控制版本
// e.g. Gradle是基于Groovy的构建语言,本身也是JVM语言
}
bootRun {
addResources = false
systemProperties = System.properties
main = 'com.avcdata.Application' // 程序运行的主文件,每个项目需指定一个运行入口
}
repositories {
mavenLocal()
maven { url 'http://jcenter.bintray.com/' }
maven { url 'http://repo1.maven.org/maven2/' }
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'http://repo.spring.io/libs-milestone/' }
maven { url 'http://repo.spring.io/release' }
maven { url 'http://repo.spring.io/milestone' }
}
dependencies {
compile 'com.zaxxer:HikariCP:2.6.1'
compile 'org.projectlombok:lombok:1.16.12'
compile 'mysql:mysql-connector-java:6.0.5'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0'
compile 'tk.mybatis:mapper-spring-boot-starter:1.0.0'
compile 'com.github.pagehelper:pagehelper-spring-boot-starter:1.1.0'
testCompile ( 'org.springframework.boot:spring-boot-starter-test' )
}
二、在项目中集成一些工作
①引入通用mapper,在指定位置。
如图所示:在com.avcdata.util下
其中MyMapper的源代码为:
package com.avcdata.util;/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* 继承自己的MyMapper
*
* @author liuzh
* @since 2015-09-06 21:53
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
//TODO
//FIXME 特别注意,该接口不能被扫描到,否则会出错
}
②在resources下创建一个mapper目录
③书写application.yml文件
spring:
datasource:
url: jdbc:mysql://192.168.2.200/jdbc_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
username: root
password: new.1234
max-lifetime: 1765000
maximum-pool-size: 15
minimum-idle: 2
connection-timeout: 1765000
mybatis:
type-aliases-package: com.avcdata.model # 配置Bean对应的别名目录
mapper-locations: classpath:mapper/*.xml # 配置mapper对应目录
configuration:
call-setters-on-nulls: true # 为null不清除
map-underscore-to-camel-case: true #开启驼峰命名
mapper:
#通用Mapper目录
mappers:
- com.avcdata.util.MyMapper # 配置MyMapper目录
not-empty: false
identity: MYSQL
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
logging:
# 日志打印级别配置
config: classpath:logback.xml
三、初始化业务相关的Dao层
①、根据表结构,去建立一个Bean
此为一张表,其中表名为user,id为主键,username和password为两个字段。所对应的Bean放在com.avcdata.model下,Bean名为User
package com.avcdata.model;
import lombok.*;
import org.apache.ibatis.type.Alias;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* Created by huangcheng on 2017/3/24.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Alias(value = "user")
@Table(name = "user")
public class User {
@Id
private Integer id;
@Column(name = "username")
private String username; // 因为开启了驼峰命名,所以password不需要@column
private String password;
}
②创建对应的UserMapper
1、在com.avcdata.mapper下创建一个UserMapper
UserMapper继承MyMapper<User>
代码如下:
package com.avcdata.dao;
import com.avcdata.model.User;
import com.avcdata.util.MyMapper;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
*
* Created by huangcheng on 2017/3/24.
*/
//继承了通用MyMapper,则可以根据Bean实现简单的增删改查
@Mapper
public interface UserMapper extends MyMapper<User> {
List<User> query(String s);
}
2、在resources中创建一个Usermapper.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.avcdata.dao.UserMapper">
<select id="query" parameterType="java.lang.String"
resultType="user">
SELECT
username ,
password
FROM user
</select>
</mapper>
至此,实现了Dao层。
四、简单实现Controller和Service
①、初始化一个Service命名为UserService
源代码如下:
package com.avcdata.service;
import com.avcdata.dao.UserMapper;
import com.avcdata.model.PageInfoParam;
import com.avcdata.model.User;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* Created by huangcheng on 2017/3/24.
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> query(PageInfoParam pageInfoParam){
PageHelper.startPage(pageInfoParam.getPageSize(), pageInfoParam.getCurrentPage());
return userMapper.selectAll();
}
}
②、初始化一个Controller,命名为:UserController
源代码如下:
package com.avcdata.controller;
import com.avcdata.model.PageInfoParam;
import com.avcdata.model.User;
import com.avcdata.service.UserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
*
* Created by huangcheng on 2017/3/24.
*/
@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "/query", method = RequestMethod.POST)
public PageInfo<User> query(@RequestBody PageInfoParam pageInfoParam){
log.info("currentPage:{}, pageSize:{}", pageInfoParam.getCurrentPage(), pageInfoParam.getPageSize());
return new PageInfo<>(userService.query(pageInfoParam));
}
}
五、启动服务并测试
①、启动服务
②、用postman发送请求
其中pageSize为每页数量,currentPage为当前页
返回得到相对应的ResponseBody,携带了分页信息的全部查询:
{
"pageNum": 0,
"pageSize": 0,
"size": 1,
"startRow": 1,
"endRow": 1,
"total": 1,
"pages": 0,
"list": [
{
"id": 1,
"username": "hc",
"password": "1234"
}
],
"prePage": 0,
"nextPage": 0,
"isFirstPage": false,
"isLastPage": true,
"hasPreviousPage": false,
"hasNextPage": false,
"navigatePages": 8,
"navigatepageNums": [],
"navigateFirstPage": 0,
"navigateLastPage": 0,
"firstPage": 0,
"lastPage": 0
}