大家好,又見面了,我是你們的朋友全棧君。
本篇主要介紹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://javaforall.cn/126704.html原文連結:https://javaforall.cn