这里对mybatisplus中配置遇到的问题及extent、implement所导入的包也为大家方便引入依赖
1 引入相关依赖
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter
mysql
mysql-connector-java
5.1.47
runtime
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
druid-spring-boot-starter
1.1.20
com.baomidou
mybatisplus-spring-boot-starter
1.0.5
com.baomidou
mybatis-plus
3.2.0
com.baomidou
mybatis-plus-boot-starter
3.3.1
com.baomidou
mybatis-plus-core
3.2.0
org.projectlombok
lombok
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
com.baomidou
mybatis-plus-extension
3.2.0
2 yml文件配置
部分小伙伴 mysql-connector-java 版本过高,需要将 driver-class-name换成:com.mysql.cj.jdbc.Driver
server:
port: 9999
# 配置数据源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true
username: root
password: 123456
3 相关的数据库表数据
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tb_area
-- ----------------------------
DROP TABLE IF EXISTS `tb_area`;
CREATE TABLE `tb_area` (
`area_id` int(2) NOT NULL AUTO_INCREMENT COMMENT '自增id',
`area_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '区域名称',
`priority` int(2) NOT NULL DEFAULT 0 COMMENT '优先级',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_time` datetime NULL DEFAULT NULL COMMENT '最后修改时间',
PRIMARY KEY (`area_id`) USING BTREE,
UNIQUE INDEX `UK_AREA`(`area_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
代码环节
1 目录结构
2 dao数据
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class BaseEntity extends Model {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@Override
protected Serializable pkVal() {
return super.pkVal();
}
}
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_area")
public class Book extends BaseEntity implements Serializable {
@TableId(value = "area_id", type = IdType.AUTO)
private Integer areaId;
private String areaName;
private int priority;
}
3 service层
需要注意的是import的对象是什么(吃过这里的亏)
import com.alnex.myOwn.dao.Book;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IBookService extends IService {
}
import org.springframework.stereotype.Service;
import com.alnex.myOwn.dao.Book;
import com.alnex.myOwn.mapper.BookMapper;
import com.alnex.myOwn.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@Service
public class BookServerImpl extends ServiceImpl implements IBookService{
}
4 map包下
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface SuperMapper extends BaseMapper {
}
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.alnex.myOwn.dao.Book;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface BookMapper extends BaseMapper {
@Select("SELECT * FROM `tb_area`")
List selectList();
}
5 controller包下
import javax.annotation.Resource;
import java.util.List;
import org.springframework.web.bind.annotation.*;
import com.alnex.myOwn.dao.Book;
import com.alnex.myOwn.service.IBookService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/book")
public class IndexController {
@Resource
private IBookService bookServer;
@GetMapping("/list/{pageNum}/{pageSize}")
public Object index(@PathVariable("pageNum") int pageNum,@PathVariable("pageSize") int pageSize){
System.out.println("pageNum = " + pageNum);
System.out.println("pageSize = " + pageSize);
log.info("----- baseMapper 自带分页 ------");
Page pg = new Page<>(pageNum, pageSize);
IPage bookIPage = bookServer.page(pg);
log.info("总条数 ------> [{}]" , bookIPage.getTotal());
log.info("当前页数 ------> [{}]" , bookIPage.getCurrent());
log.info("当前每页显示数 ------> [{}]" , bookIPage.getSize());
log.info("当前页数据 ------> [{}]" , bookIPage.getRecords());
print(bookIPage.getRecords());
log.info("----- Book 列表数据展示 ------");
List list = bookServer.list();
log.info("list 数据 ------> {[]} " + list);
return bookIPage;
}
private void print(List list) {
if (!CollectionUtils.isEmpty(list)) {
for (Book t : list) {
log.info("Book 数据为 ----> [{}]",t);
log.info("[{}]",t.getCreateTime());
log.info("[{}]",t.getUpdateTime());
}
}
}
@GetMapping("/getOne/{areaId}")
public Object getOne(@PathVariable("areaId") int areaId){
System.out.println(areaId);
//方法一
Book other = bookServer.getById(areaId);
log.info("book 数据为 ------> [{}]" , other);
System.out.println();
//方法二
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("area_id",areaId);
Book book = bookServer.getOne(queryWrapper);
log.info("book1 数据为 ------> [{}]" , book);
return book;
}
@PutMapping("/save")
public Object save(@RequestBody Book book){
return bookServer.save(book);
}
@DeleteMapping("/del/{areaId}")
public Object del(@PathVariable("areaId") int areaId){
boolean b;
//方式一
// b = bookServer.removeById(areaId);
//方式二
QueryWrapper queryWrapper =new QueryWrapper<>();
queryWrapper.eq("area_id",areaId);
b = bookServer.remove(queryWrapper);
return b;
}
@PutMapping("/update")
public Object update(@RequestBody Book book){
return bookServer.updateById(book);
}
//批量新增或者修改方法,判断ID是否存在,如果ID不存在执行新增,如果ID存在先执行查询语句,查询结果为空新增,否则修改。
@PutMapping("/addMore")
public Object addList(@RequestBody List list){
return bookServer.saveOrUpdateBatch(list);
}
}
6 config包下【重要】
在之前配置config 时只配置mybatisplus 的分页插件,发现在启动时一直报 Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required 的错误
附查询的相关资料:https://www.cnblogs.com/hawk0035/p/3337283.html?utm_source=tuicool
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.incrementer.DB2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
@Configuration
@MapperScan("com.alnex.myOwn.mapper")
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件
* 文档:http://mp.baomidou.com
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, GlobalConfig globalConfig) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactory.setConfiguration(configuration);
PaginationInterceptor pagination = new PaginationInterceptor();
sqlSessionFactory.setPlugins(pagination);
sqlSessionFactory.setGlobalConfig(globalConfig);
return sqlSessionFactory.getObject();
}
@Bean
public GlobalConfig globalConfig() {
GlobalConfig config = new GlobalConfig();
GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
dbConfig.setKeyGenerator(new DB2KeyGenerator());
config.setDbConfig(dbConfig);
return config;
}
}
以上就是mybatisplus的相关总结,如有问题,欢迎留言讨论~