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);
    }
}


第一次發博客,不足之處,敬請諒解,如有不清楚的地方,歡迎評論一起探討!!!謝謝大家,晚安

發佈了33 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章