本篇主要介绍mybatisplus的简单应用
这里对mybatisplus中配置遇到的问题及extent、implement所导入的包也为大家方便引入依赖
1 引入相关依赖
依赖只是参考,每人的仓库不同,代码块内容仅作参考
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
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<T extends Model> 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<Book> 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<Book> {
}
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<BookMapper, Book> implements IBookService{
}
4 map包下
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface SuperMapper<T> extends BaseMapper<T> {
}
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<Book> {
@Select("SELECT * FROM `tb_area`")
List<Book> 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<Book> pg = new Page<>(pageNum, pageSize);
IPage<Book> 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<Book> list = bookServer.list();
log.info("list 数据 ------> {[]} " + list);
return bookIPage;
}
private <T> void print(List<Book> 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<Book> 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<Book> 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<Book> 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分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@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的相关总结,如有问题,欢迎留言讨论~
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10626.html