Springboot整合mybatis及分页查询、定时任务)

整了一整天,看了一位前辈的博客,在此基础上加上本人的理解及创作,哪位前辈忘记了,望谅解!不多说,直接上代码。Springboot整合mybatis及分页查询、定时任务)

以上是项目的整体结构,下面是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.yan</groupId>
<artifactId>daydayup</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>

<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.6.RELEASE</version>
</parent>

<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>


<!-- 添加mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- 添加分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>

</dependencies>



<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!-- spring热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>


下面是配置文件application.yml:# Server settings
server:
port: 80
address: 127.0.0.1

# SPRING PROFILES
spring:
# HTTP ENCODING
http:
encoding.charset: UTF-8
encoding.enable: true
encoding.force: true


# DATASOURCE
datasource:
driverClass: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/taotao?useUnicode=true&characterEncoding=utf-8
username: root
password: 1234
# LOGGING
logging:
level:
org.apache.ibatis:DEBUG

接着是config的配置:

package com.yan.common.config;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
* MyBatis扫描接口,使用的tk.mybatis.spring.mapper.MapperScannerConfigurer,
* 如果你不使用通用Mapper, 可以改为org.xxx...
*
* @author yanxiangshang
* @since 2017-06-24 14:46
*/
@Configuration
public class MyBatisMapperScannerConfig {

/**
* 配置pageHelper分页支持
* @return
*/
@Bean
public PageHelper pageHepler() {
System.out.println("MyBatisMapperScannerConfig.pageHelper Opening... ");
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
pageHelper.setProperties(properties);
return pageHelper;
}

/**
* spring-mybatis整合
* @return
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.*.dao");
Properties properties = new Properties();
properties.setProperty("mappers", "com.yan.common.BaseDao");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}

}


项目的BaseDao为通用mapper,继承该类即可:

package com.yan.common;


import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;


public interface BaseDao<T> extends Mapper<T>,MySqlMapper<T>{


}

BaseResp文件:

package com.yan.common;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
 * 返回统一处理类(用于和分页处理返回前台使用)
 * Created by yanxiangshang
 */
public class BaseResp<T> {
// 返回码
private int ret = 0;
// 返回信息
private String message;


private Data data = new Data();


public class Data {
// 数据总数
Integer total = 0;
// 当前页(默认第一页)
        int currPage = 1;
        // 数据集合
Collection<T> items = new ArrayList<T>();


public Integer getTotal() {
return total;
}


public void setTotal(Integer total) {
this.total = total;
}


public Collection<T> getItems() {
return items;
}


public void setItems(Collection<T> items) {
this.items = items;
this.total = items.size();
}


public int getCurrPage() {
return currPage;
}


public void setCurrPage(int currPage) {
this.currPage = currPage;
}


@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}


public BaseResp() {


}
public BaseResp(int ret, String message) {
this.ret = ret;
this.message = message;
        this.data =null;
}
// 供只返回一个对象时构造
public BaseResp(T t) {
this.data.items.add(t);
this.data.total = 1;
this.message = "成功";
}
// 供返回多个对象时构造
/*public BaseResp(Collection<T> items) {
this.data.items = items;
this.message = "成功";
this.data.total = items.size();
}*/
// 供返回多个对象时构造
public BaseResp(Collection<T> items, int total) {
this(items,total,1);
}

// 供返回多个对象时构造
public BaseResp(Collection<T> items, int total, int currPage) {
this.data.items = items;
this.message = "成功";
this.data.total = total;
this.data.currPage = currPage;
}
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}

以下各个类的信息:

package com.yan.myboot.controller;


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;


import com.github.pagehelper.PageInfo;
import com.yan.common.BaseController;
import com.yan.common.BaseResp;
import com.yan.myboot.entity.User;
import com.yan.myboot.service.UserService;


@RestController//rest风格的返回参数
@RequestMapping("/test/user")
public class UserController extends BaseController{
@Autowired
private UserService userService;

/**
* 分页查询信息
* @param page 当前页
* @param rows 每页显示多少条
* @return
*/
@RequestMapping(value="/find",method = {RequestMethod.POST,RequestMethod.GET})
public BaseResp<User> regiester(@RequestParam("page")Integer page,@RequestParam("rows")Integer rows){
//查询分页信息
PageInfo<User> infos = userService.queryAll(page,rows);
return new BaseResp<User>(infos.getList(), (int)infos.getTotal(),infos.getPageNum());
}

/**
* 插入数据
* @param total 插入的条数
* @return
*/
@SuppressWarnings("rawtypes")
@RequestMapping(value="/insert",method = {RequestMethod.POST,RequestMethod.GET})
public BaseResp insert(@RequestParam("total")Integer total){
boolean insertUser = userService.insertUser(total);
if (!insertUser) {
logger.error("查询失败!");
return new BaseResp(10000, "失败");
}
return new BaseResp(0,"成功");
}

/**
* 分页查询信息
* @param page 当前页
* @param rows 每页显示多少条
* @return
*/
@RequestMapping(value="/all",method = {RequestMethod.POST,RequestMethod.GET})
public BaseResp<User> findAll(@RequestParam("page")Integer page,@RequestParam("rows")Integer rows){
// userService.saveUser(null);
PageInfo<User> infos = userService.finlAll(page, rows);
return new BaseResp<User>(infos.getList(), (int)infos.getTotal(),infos.getPageNum());
}
}

package com.yan.myboot.service.impl;


import java.util.ArrayList;
import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yan.myboot.dao.UserDao;
import com.yan.myboot.entity.User;
import com.yan.myboot.service.UserService;


@Transactional(readOnly = true)//只读(查询适用)
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;


/**
* 查询所有的信息
*/
@Override
public PageInfo<User> queryAll(int page, int rows) {
PageHelper.startPage(page, rows);
List<User> userList = userDao.selectAll();
PageInfo<User> pageInfo = new PageInfo<User>(userList);
return pageInfo;
}


/**
* 添加数据信息
*/
@Transactional
@Override
public boolean insertUser(int n) {
List<User> list = new ArrayList<User>();
for (int i = 0; i < n; i++) {
User user = new User();
user.setAge(i);
user.setName("xiangshang" + i);
list.add(user);
}
int insertList = userDao.insertList(list);
return insertList == 0 ? false : true;
}


/**
* 分页查询信息
*/
@Override
public PageInfo<User> finlAll(int page, int rows) {
PageHelper.startPage(page, rows);
List<User> userList = userDao.selectByState();
PageInfo<User> pageInfo = new PageInfo<User>(userList);
return pageInfo;
}


}

package com.yan.myboot.dao;




import java.util.List;


import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;


import com.yan.common.BaseDao;
import com.yan.common.DaoException;
import com.yan.myboot.entity.User;


@Mapper
public interface UserDao extends BaseDao<User>{
@Results({ //2
         @Result(property = "id", column = "id"), //2
         @Result(property = "name", column = "name"),
         @Result(property = "age", column = "age")
})
@Select("select * from USER")
public List<User> selectByState() throws DaoException;
}


package com.yan.myboot.entity;


import java.io.Serializable;


import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@SuppressWarnings("serial")
public class User implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;


public Integer getId() {
return id;
}


public void setId(Integer id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public Integer getAge() {
return age;
}


public void setAge(Integer age) {
this.age = age;
}


}


package com.yan.myboot;


import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * 定时任务类
 * @author yanup
 *
 */
@Component
public class MyTask {
/**
* 定时任务每十秒执行一次
*/
private static final String TEST_CORE ="0/10 * * * * ? ";

//@Scheduled注解为定时任务,cron表达式里写执行的时机(即什么时间执行)
@Scheduled(cron = TEST_CORE)
public void testTask(){
System.out.println("定时每十秒启动一次。。。");
}
}


下面也是重要的启动信息如下:

package com.yan;




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;


@EnableScheduling//此注解配置定时任务
@SpringBootApplication
public class Application  extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


第一次发博客,不足之处,敬请谅解,如有不清楚的地方,欢迎评论一起探讨!!!谢谢大家,晚安