1.1,idea创建,点击new project,然后一路next下去
1.2,设置maven自动导入,setting文件添加阿里云镜像
1.3,添加pom依赖,让工程跑起来
在添加build
同时添加mybatis整合springboot依赖,跟mysql依赖
1.3,将自动生成代码文件放入resource资源文件下,文件名为generatorConfig.xml
xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
password="123">
targetProject="src/main/java">
targetProject="src/main/java">
targetPackage="com.example.mapper"
targetProject="src/main/java">
schema=""tableName="userinfo">
2.1 建表语句如下:
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2,修改generatorConfig.xml文件,修改文件后如下
?xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
password="123">
targetProject="src/main/java">
targetProject="src/main/java">
targetPackage="com.example.mapper"
targetProject="src/main/java">
schema=""tableName="user">
2.3,添加application.properties的数据源
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.4.点击maven里的生成按钮,生成mapper等文件
2.5.生成后的目录如下,并且工程启动没有错误
2.6 DemoApplication启动类上添加注解
@MapperScan(basePackages= {"com.demo.mapper"})
@ComponentScan(basePackages= {"com.demo"})
3.1 service层的接口以及实现类
public interfaceUserService {
List
}
@Service
public class UserServiceImplimplementsUserService {
@Autowired
UserMapperuserMapper;
@Override
publicList
UserExample userExample = new UserExample();
userExample.setDistinct(true);
return userMapper.selectByExample(userExample);
}
}
3.2 controller如下,启动浏览器或者postman可测试返回数据
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserServiceuserServiceImpl;
/**
* 查询
* @return
*/
@RequestMapping(value="/demo",method= RequestMethod.GET)
@ResponseBody
publicObjectgetUsers(){
returnuserServiceImpl.getAll();
}
}
3.3 利用RowBounds进行分页查询
一,usermapper与usermapper.xml添加如下代码
List
二,userservice与userserviceimpl分别添加如下代码
List
@Override
public List
RowBounds rowBounds = newRowBounds(pageNo,pageSize);
UserExample userExample =newUserExample();
userExample.setDistinct(true);
return userMapper.selectByExampleWithBounds(userExample,rowBounds);
}
二.Usercontroller添加如下代码
/**
* 利用mybatis的rowbounds分页类,分页查询
*/
@RequestMapping(value="/page",method= RequestMethod.GET)
@ResponseBody
public ObjectgetPage(@RequestParam(name="pageSize") String pageSize,
@RequestParam(name="pageNo") String pageNo){
try{
String size = pageSize;
int pageSizes=5,nos=1;
if(StringUtils.isNotBlank(size)){
pageSizes = Integer.parseInt(pageSize);
}
String no = pageNo;
if(StringUtils.isNotBlank(no)){
nos = Integer.parseInt(no);
}
returnuserServiceImpl.getPage(pageSizes,nos);
}catch(Exception ex){
ex.getMessage();
}
return null;
}
三.请求路径上添加pagesize跟pageno这连个参数,可正常返回分页
4.1 pom.xml添加依赖如下
4.2 resource资源目录下添加logback.xml文件如下
xml version="1.0"encoding="UTF-8"?>
4.3.启动项目,访问分页查询接口,可看到如下日子生成文件
5.1 DemoApplication添加注解
@EnableScheduling
5.2 添加定时启动类
@Component
public class Task {
Logger logger= LoggerFactory.getLogger(Task.class);
@Autowired
UserServiceuserServiceImpl;
@Scheduled(cron="0/5 * * * * ?")
public voidtest(){
//加入fastJson依赖
/*
*/
List
String str = JSONObject.toJSONString(users);
logger.info(str);
}
}
6.1pom.xml文件添加依赖
6.2,application.properties的配置文件如下:
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM t_user
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.druid.useGlobalDataSourceStat=true
#mybatis.mapperLocations=classpath:mybatis/*.xml
Task类
package com.demo.job;
import com.alibaba.fastjson.JSONObject;
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class Task {
Logger logger= LoggerFactory.getLogger(Task.class);
@Autowired
UserServiceuserServiceImpl;
@Scheduled(cron="0 30 * * * ?")
public voidtest(){
//加入fastJson依赖
/*
*/
List
String str = JSONObject.toJSONString(users);
logger.info(str);
}
}
UserMapper
package com.demo.mapper;
import com.demo.pojo.User;
import com.demo.pojo.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
intcountByExample(UserExample example);
int deleteByExample(UserExample example);
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
List
List
UserselectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
UserMapper.xml
xml version="1.0"encoding="UTF-8"?>
mapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
and ${criterion.condition}
and ${criterion.condition} #{criterion.value}
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
and ${criterion.condition}
#{listItem}
and ${criterion.condition}
and ${criterion.condition} #{criterion.value}
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
and ${criterion.condition}
#{listItem}
id, username, password
delete from user
where id = #{id,jdbcType=INTEGER}
delete from user
insert into user (id, username, password
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
insert into user
id,
username,
password,
#{id,jdbcType=INTEGER},
#{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
update user
id = #{record.id,jdbcType=INTEGER},
username = #{record.username,jdbcType=VARCHAR},
password = #{record.password,jdbcType=VARCHAR},
update user
set id = #{record.id,jdbcType=INTEGER},
username = #{record.username,jdbcType=VARCHAR},
password = #{record.password,jdbcType=VARCHAR}
update user
username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
where id = #{id,jdbcType=INTEGER}
update user
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
User
package com.demo.pojo;
public class User {
privateIntegerid;
private Stringusername;
private Stringpassword;
public IntegergetId() {
returnid;
}
public voidsetId(Integer id) {
this.id= id;
}
publicStringgetUsername() {
returnusername;
}
public voidsetUsername(String username) {
this.username= username ==null?null: username.trim();
}
publicStringgetPassword() {
returnpassword;
}
public voidsetPassword(String password) {
this.password= password ==null?null: password.trim();
}
}
UserExample
package com.demo.pojo;
import java.util.ArrayList;
import java.util.List;
public class UserExample {
protectedStringorderByClause;
protected boolean distinct;
protected List
public UserExample() {
oredCriteria=newArrayList
}
public voidsetOrderByClause(String orderByClause) {
this.orderByClause= orderByClause;
}
publicStringgetOrderByClause() {
returnorderByClause;
}
public voidsetDistinct(booleandistinct) {
this.distinct= distinct;
}
public booleanisDistinct() {
returndistinct;
}
publicList
returnoredCriteria;
}
public voidor(Criteria criteria) {
oredCriteria.add(criteria);
}
publicCriteriaor() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
publicCriteriacreateCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() ==0) {
oredCriteria.add(criteria);
}
returncriteria;
}
protectedCriteriacreateCriteriaInternal() {
Criteria criteria = newCriteria();
return criteria;
}
public voidclear() {
oredCriteria.clear();
orderByClause=null;
distinct=false;
}
protected abstract static classGeneratedCriteria {
protectedList
protected GeneratedCriteria() {
super();
criteria=newArrayList
}
public booleanisValid() {
returncriteria.size() >0;
}
publicList
returncriteria;
}
publicList
returncriteria;
}
protected voidaddCriterion(String condition) {
if(condition ==null) {
throw newRuntimeException("Value for condition cannot be null");
}
criteria.add(newCriterion(condition));
}
protected voidaddCriterion(String condition,Object value,String property) {
if(value ==null) {
throw newRuntimeException("Value for "+ property + " cannot be null");
}
criteria.add(newCriterion(condition,value));
}
protected voidaddCriterion(String condition,Object value1,Object value2,String property) {
if(value1 ==null|| value2 ==null) {
throw newRuntimeException("Between values for "+ property + " cannot be null");
}
criteria.add(newCriterion(condition,value1,value2));
}
publicCriteriaandIdIsNull() {
addCriterion("id is null");
return (Criteria)this;
}
publicCriteriaandIdIsNotNull() {
addCriterion("id is not null");
return (Criteria)this;
}
publicCriteriaandIdEqualTo(Integer value) {
addCriterion("id =",value,"id");
return (Criteria)this;
}
publicCriteriaandIdNotEqualTo(Integer value) {
addCriterion("id <>",value,"id");
return (Criteria)this;
}
publicCriteriaandIdGreaterThan(Integer value) {
addCriterion("id >",value,"id");
return (Criteria)this;
}
publicCriteriaandIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=",value,"id");
return (Criteria)this;
}
publicCriteriaandIdLessThan(Integer value) {
addCriterion("id <",value,"id");
return (Criteria)this;
}
publicCriteriaandIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=",value,"id");
return (Criteria)this;
}
publicCriteriaandIdIn(List
addCriterion("id in",values,"id");
return (Criteria)this;
}
publicCriteriaandIdNotIn(List
addCriterion("id not in",values,"id");
return (Criteria)this;
}
publicCriteriaandIdBetween(Integer value1,Integer value2) {
addCriterion("id between",value1,value2,"id");
return (Criteria)this;
}
publicCriteriaandIdNotBetween(Integer value1,Integer value2) {
addCriterion("id not between",value1,value2,"id");
return (Criteria)this;
}
publicCriteriaandUsernameIsNull() {
addCriterion("username is null");
return (Criteria)this;
}
publicCriteriaandUsernameIsNotNull() {
addCriterion("username is not null");
return (Criteria)this;
}
publicCriteriaandUsernameEqualTo(String value) {
addCriterion("username =",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameNotEqualTo(String value) {
addCriterion("username <>",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameGreaterThan(String value) {
addCriterion("username >",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameGreaterThanOrEqualTo(String value) {
addCriterion("username >=",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameLessThan(String value) {
addCriterion("username <",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameLessThanOrEqualTo(String value) {
addCriterion("username <=",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameLike(String value) {
addCriterion("username like",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameNotLike(String value) {
addCriterion("username not like",value,"username");
return (Criteria)this;
}
publicCriteriaandUsernameIn(List
addCriterion("username in",values,"username");
return (Criteria)this;
}
publicCriteriaandUsernameNotIn(List
addCriterion("username not in",values,"username");
return (Criteria)this;
}
publicCriteriaandUsernameBetween(String value1,String value2) {
addCriterion("username between",value1,value2,"username");
return (Criteria)this;
}
publicCriteriaandUsernameNotBetween(String value1,String value2) {
addCriterion("username not between",value1,value2,"username");
return (Criteria)this;
}
publicCriteriaandPasswordIsNull() {
addCriterion("password is null");
return (Criteria)this;
}
publicCriteriaandPasswordIsNotNull() {
addCriterion("password is not null");
return (Criteria)this;
}
publicCriteriaandPasswordEqualTo(String value) {
addCriterion("password =",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordNotEqualTo(String value) {
addCriterion("password <>",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordGreaterThan(String value) {
addCriterion("password >",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordGreaterThanOrEqualTo(String value) {
addCriterion("password >=",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordLessThan(String value) {
addCriterion("password <",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordLessThanOrEqualTo(String value) {
addCriterion("password <=",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordLike(String value) {
addCriterion("password like",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordNotLike(String value) {
addCriterion("password not like",value,"password");
return (Criteria)this;
}
publicCriteriaandPasswordIn(List
addCriterion("password in",values,"password");
return (Criteria)this;
}
publicCriteriaandPasswordNotIn(List
addCriterion("password not in",values,"password");
return (Criteria)this;
}
publicCriteriaandPasswordBetween(String value1,String value2) {
addCriterion("password between",value1,value2,"password");
return (Criteria)this;
}
publicCriteriaandPasswordNotBetween(String value1,String value2) {
addCriterion("password not between",value1,value2,"password");
return (Criteria)this;
}
}
public static classCriteriaextendsGeneratedCriteria {
protectedCriteria() {
super();
}
}
public static classCriterion {
privateStringcondition;
private Objectvalue;
private ObjectsecondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private StringtypeHandler;
public StringgetCondition() {
returncondition;
}
publicObjectgetValue() {
returnvalue;
}
publicObjectgetSecondValue() {
returnsecondValue;
}
public booleanisNoValue() {
returnnoValue;
}
public booleanisSingleValue() {
returnsingleValue;
}
public booleanisBetweenValue() {
returnbetweenValue;
}
public booleanisListValue() {
returnlistValue;
}
publicStringgetTypeHandler() {
returntypeHandler;
}
protectedCriterion(String condition) {
super();
this.condition= condition;
this.typeHandler=null;
this.noValue=true;
}
protectedCriterion(String condition,Object value,String typeHandler) {
super();
this.condition= condition;
this.value= value;
this.typeHandler= typeHandler;
if (valueinstanceofList>) {
this.listValue=true;
}else{
this.singleValue=true;
}
}
protectedCriterion(String condition,Object value) {
this(condition,value, null);
}
protectedCriterion(String condition,Object value,Object secondValue,String typeHandler) {
super();
this.condition= condition;
this.value= value;
this.secondValue= secondValue;
this.typeHandler= typeHandler;
this.betweenValue=true;
}
protectedCriterion(String condition,Object value,Object secondValue) {
this(condition,value,secondValue, null);
}
}
}
UserService
package com.demo.service;
import com.demo.pojo.User;
import java.util.List;
public interface UserService {
List
List
List
int insert(String userName,String password);
int updateUser(intid);
}
UserServiceImpl
package com.demo.service.impl;
import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.pojo.UserExample;
import com.demo.service.UserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImplimplementsUserService {
@Autowired
UserMapperuserMapper;
@Override
publicList
UserExample userExample = new UserExample();
userExample.setDistinct(true);
return userMapper.selectByExample(userExample);
}
@Override
publicList
RowBounds rowBounds = new RowBounds(pageNo,pageSize);
UserExample userExample =newUserExample();
userExample.setDistinct(true);
return userMapper.selectByExampleWithBounds(userExample,rowBounds);
}
@Override
publicList
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameEqualTo(name);
return userMapper.selectByExample(userExample);
}
@Override
public intinsert(String userName,String password) {
User user = newUser();
user.setUsername(userName);
user.setPassword(password);
return userMapper.insert(user);
}
@Override
public intupdateUser(intid) {
User user = newUser();
user.setId(id);
user.setUsername("修改");
user.setPassword("111");
return userMapper.updateByPrimaryKey(user);
}
}
UserController
package com.demo.web;
import com.demo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserServiceuserServiceImpl;
/**
* 查询
* @return
*/
@RequestMapping(value="/demo",method= RequestMethod.GET)
@ResponseBody
publicObjectgetUsers(){
returnuserServiceImpl.getAll();
}
/**
* 利用mybatis的rowbounds分页类,分页查询
*/
@RequestMapping(value="/page",method= RequestMethod.GET)
@ResponseBody
publicObjectgetPage(@RequestParam(name="pageSize") String pageSize,
@RequestParam(name="pageNo") String pageNo){
try{
String size = pageSize;
int pageSizes=5,nos=1;
if(StringUtils.isNotBlank(size)){
pageSizes = Integer.parseInt(pageSize);
}
String no = pageNo;
if(StringUtils.isNotBlank(no)){
nos = Integer.parseInt(no);
}
returnuserServiceImpl.getPage(pageSizes,nos);
}catch(Exception ex){
ex.getMessage();
}
return null;
}
/**
* 按条件查询
*/
@RequestMapping(value="/condition/{name}",method= RequestMethod.GET)
@ResponseBody
publicObjectgetCondition(@PathVariableString name){
returnuserServiceImpl.getCondition(name);
}
/**
* 增加user
*/
@RequestMapping(value="/save",method= RequestMethod.GET)
@ResponseBody
publicObjectsave(@RequestParam(name="username") String username,
@RequestParam(name="password") String password){
returnuserServiceImpl.insert(username,password);
}
/**
* 根据id修改user
*/
@RequestMapping(value="/update/{id}",method= RequestMethod.GET)
@ResponseBody
publicObjectupdateUser(@PathVariableintid){
returnuserServiceImpl.updateUser(id);
}
}
demoApplication
package com.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@MapperScan(basePackages= {"com.demo.mapper"})
@ComponentScan(basePackages= {"com.demo"})
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static voidmain(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
Application.properties
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM t_user
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.druid.useGlobalDataSourceStat=true
#mybatis.mapperLocations=classpath:mybatis/*.xml
GeneratorConfig.xml
xml version="1.0"encoding="UTF-8"?>
generatorConfiguration
PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
connectionURL="jdbc:mysql://localhost:3306/test"userId="root"
password="123">
targetProject="src/main/java">
targetProject="src/main/java">
targetPackage="com.demo.mapper"
targetProject="src/main/java">
schema=""tableName="user">
Logback.xml
xml version="1.0"encoding="UTF-8"?>
Pom.xml
xml version="1.0"encoding="UTF-8"?>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
8.1添加pom.xml依赖
8.2UserController添加注解
@Api("测试swagger")
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserService userServiceImpl;
/**
* 查询
* @return
*/
@ApiOperation("查询")
@RequestMapping(value = "/demo",method = RequestMethod.GET)
@ResponseBody
public Object getUsers(){
return userServiceImpl.getAll();
}
/**
* 利用mybatis的rowbounds分页类,分页查询
*/
@ApiOperation("利用mybatis的rowbounds分页类,分页查询")
@RequestMapping(value = "/page",method = RequestMethod.GET)
@ResponseBody
public Object getPage(@RequestParam(name = "pageSize") String pageSize,
@RequestParam(name = "pageNo") String pageNo){
try{
String size = pageSize;
int pageSizes=0,nos=0;
if(StringUtils.isNotBlank(size)){
pageSizes = Integer.parseInt(pageSize);
}
String no = pageNo;
if(StringUtils.isNotBlank(no)){
nos = Integer.parseInt(no);
}
return userServiceImpl.getPage(pageSizes,nos);
}catch (Exception ex){
ex.getMessage();
}
return null;
}
8.3,启动项目,访问http://localhost:8080/swagger-ui.html#/
9.1pom.xml文件加入依赖
9.2 application.properties加入redis配置,前提要有redis服务
#连超时设置
default.redis.timeout=15000
#是否使用连接池
default.redis.usePool = true
#host&port
default.redis.nodes=192.168.0.208:7000
9.3 添加几个类
JedisConfig配置类如下
package com.demo.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class JedisConfig {
@Autowired
Environment evn;
@Bean
public ShardedJedisPool shardedJedisPool(){
String servers = evn.getProperty("default.redis.nodes");
int timeOut = Integer.parseInt(evn.getProperty("default.redis.timeout"));
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(2);
List
String[] split = servers.split(":");
JedisShardInfo jedisShardInfo = new JedisShardInfo(split[0],Integer.parseInt(split[1]),timeOut);
jedisShardInfos.add(jedisShardInfo);
return new ShardedJedisPool(config,jedisShardInfos);
}
}
redisUtils类如下
package com.demo.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import java.util.List;
@Component
public class RedisUtil {
@Autowired
ShardedJedisPool pool;
public void set(String key,String value) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = pool.getResource();
if (shardedJedis != null) {
shardedJedis.set(key, value);
}
} catch (Exception ex) {
} finally {
if (shardedJedis != null) {
shardedJedis.close();
}
}
}
public String get(String key){
ShardedJedis shardedJedis = null;
try{
shardedJedis = pool.getResource();
if (shardedJedis != null){
return shardedJedis.get(key);
}
}catch (Exception ex){
}finally {
if(shardedJedis != null){
shardedJedis.close();
}
}
return "1564";
}
public List
ShardedJedis shardedJedis = null;
try {
shardedJedis = pool.getResource();
if (shardedJedis != null) {
return shardedJedis.hmget(key);
}
} catch (Exception ex) {
} finally {
if (shardedJedis != null) {
shardedJedis.close();
}
}
return null;
}
public void setList(String key,String value){
ShardedJedis shardedJedis = null;
try {
shardedJedis = pool.getResource();
if (shardedJedis != null) {
shardedJedis.set(key,value);
}
} catch (Exception ex) {
} finally {
if (shardedJedis != null) {
shardedJedis.close();
}
}
}
}
常量前缀如下
package com.demo.redis;
public class DbAndCacheContants {
public static final String USER_CACHE_PREFIX = "user:";
}
UserServiceImpl类修改如下代码
@Override
public String getCondition(String name) {
String redisName = DbAndCacheContants.USER_CACHE_PREFIX + name;
String str = redisUtil.get(redisName);
if (StringUtils.isNotBlank(str)){
return redisUtil.get(redisName);
}else {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andUsernameEqualTo(name);
List
String value = JSONObject.toJSONString(users);
redisUtil.set(redisName,value);
return value;
}
}
9.4 启动项目,swagger请求,断点调试可以看到第二次从redis里取数据
10.1 spring boot本身有添加google的guava包,如果没有,pom.xml添加如下依赖
10.2 UserServiceImpl类添加如下代码
@Override
public User selectByPrimaryKey(Integer id) {
User user = null;
try{
user = userCache.get(id);
} catch (ExecutionException e) {
e.printStackTrace();
}
return user;
}
//使用本地缓存
LoadingCache
.expireAfterWrite(2, TimeUnit.MINUTES)//缓存时间20分钟
.maximumSize(1000)//缓存对象1000个
.build(new CacheLoader
@Override
public User load(Integer id) throws Exception {
User user = userMapper.selectByPrimaryKey(id);
if(user == null){
user = new User();
}
return user;
}
});
UserService接口添加如下方法
User selectByPrimaryKey(Integer id);
UserController添加如下代码
/**
* 根据id获得user
*/
@ApiOperation("根据id获得user")
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
@ResponseBody
public Object getUser(@PathVariable int id){
return userServiceImpl.selectByPrimaryKey(id);
}
10.3启动项目,断点调试,第二次不在访问数据库,使用了本地缓存