01、新建一個springboot項目
選擇依賴和版本
SpringBoot整合lombok
lombok是一個快速生成JAVAbean的一個工具工程和生成日志的工具。未來給我們提供了很大的遍歷。
需要在idea中安裝插件和pom.xml中進(jìn)行依賴才可以使用生效:
pom.xml依賴如下:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
復(fù)制代碼
SpringBoot在依賴的過程,為什么有的要加版本號,有的不加?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>MySQL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>MyBatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
復(fù)制代碼
- mysql
- mybatis-plus 都不屬于springboot父工程管理,自然必須把自己的version加上去!
SpringBoot整合Mybatis-Plus和數(shù)據(jù)源
1、在pom.xml中依賴如下:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
復(fù)制代碼
2、準(zhǔn)備一個數(shù)據(jù)庫表kss_user
CREATE TABLE `kss_user` (
`id` int NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`real_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`gender` int DEFAULT NULL,
`birthday` date DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
復(fù)制代碼
3、配置數(shù)據(jù)源和mybatis配置
在項目的resource目錄下的Application.yaml配置如下:
server:
port: 8080
# 數(shù)據(jù)源配置
spring:
application:
name: pug-springboot-ssm
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/ssm_db?serverTimezone=GMT%2b8&useUnicode=true&useSSL=false&characterEncoding=UTF-8
username: root
password: 123456
hikari:
connection-timeout: 60000
validation-timeout: 3000
idle-timeout: 60000
login-timeout: 5
max-lifetime: 60000
maximum-pool-size: 30
minimum-idle: 10
read-only: false
# mybatis-plus配置
mybatis-plus:
configuration:
log-impl: org.Apache.ibatis.logging.stdout.StdOutImpl
mapper-locations:
- classpath*:/mapper/*.xml
復(fù)制代碼
4、在resource新建一個mapper文件用來存放mybatis的xml文件
5、springboot整合mybatis-plus
package com.ksd.pug;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.ksd.pug.mapper")
public class PugSpringbootSsmApplication {
public static void main(String[] args) {
SpringApplication.run(PugSpringbootSsmApplication.class, args);
}
}
復(fù)制代碼
SpringBoot實現(xiàn)對用戶表的CRUD操作
01、pojo
package com.ksd.pug.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName("kss_user")
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String realName;
private Integer gender;
private Date birthday;
}
復(fù)制代碼
02、mapper
package com.ksd.pug.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ksd.pug.pojo.User;
public interface UserMapper extends BaseMapper<User> {
}
復(fù)制代碼
03、service和serviceImpl
package com.ksd.pug.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ksd.pug.pojo.User;
public interface IUserService extends IService<User> {
}
復(fù)制代碼
package com.ksd.pug.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ksd.pug.mapper.UserMapper;
import com.ksd.pug.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}
復(fù)制代碼
04、controller
package com.ksd.pug.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ksd.pug.config.exception.BusinessException;
import com.ksd.pug.config.results.Code;
import com.ksd.pug.config.results.Result;
import com.ksd.pug.pojo.User;
import com.ksd.pug.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@PostMapping
public Result save(User user){
boolean flag = userService.saveOrUpdate(user);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERROR);
}
@PutMapping
public Result update(User user){
boolean flag = userService.updateById(user);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERROR);
}
@DeleteMapping("/{id}")
public Result delete(Integer id){
boolean flag = userService.removeById(id);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);
}
@GetMapping("/{id}")
public Result get(@PathVariable("id")Integer id) throws BusinessException {
User user = userService.getById(id);
// 模擬出現(xiàn)異常,使用條件控制,便于測試結(jié)果
if (id == 10) {
throw new BusinessException("查詢出錯了,請重試!",Code.GET_ERROR);
}
return new Result(null != user ? Code.GET_OK :Code.GET_ERROR,user);
}
@GetMapping("/{pageNo}/{pageSize}")
public Result getAll(@PathVariable Integer pageNo,@PathVariable Integer pageSize){
// 1、設(shè)置分頁
Page page = new Page<>(pageNo,pageSize);
// 2、設(shè)置條件
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
// 3、查詢分頁返回
IPage page1 = userService.page(page, lambdaQueryWrapper);
return new Result(null != page1 ? Code.GET_OK :Code.GET_ERROR,page1);
}
}
復(fù)制代碼
Mybatis-Plus的分頁失效問題
@Configuration
public class MybatisPlusConfig {
/**
* 新的分頁插件,一緩和二緩遵循mybatis的規(guī)則,需要設(shè)置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現(xiàn)問題(該屬性會在舊插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
復(fù)制代碼
Mybatis-Plus的創(chuàng)建時間和更新時間回填問題
- 定義個回填配置類
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill...");
//default MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
復(fù)制代碼
- 在pojo中使用@TableFiled(fill=xxx)指定回填觸發(fā)方法
package com.ksd.pug.pojo;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName("kss_user")
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
private String userName;
private String password;
private String realName;
private Integer gender;
private Date birthday;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
復(fù)制代碼
數(shù)據(jù)庫級別的解決方案
首先將字段設(shè)置為timestamp,然后設(shè)置不是null,根據(jù)當(dāng)前時間戳更新,在這里注意我們的create_time是不根據(jù)當(dāng)前時間戳更新的!這種方式雖然可以但是不建議!
在mysql低版本的時候可能會出現(xiàn)一個問題,你的sql語句無法導(dǎo)入,而導(dǎo)致這個的原因是有的他只可以設(shè)置一個timestamp(在這里提示:mysql5.7 、mysql8.0是可以的!)
Mybatis-Plus是怎么做到不寫sql但是可以實現(xiàn)CRUD操作
- 背后絕對是拼接SQL語句,然后調(diào)用mybatis底層執(zhí)行sql。
具體需要學(xué)習(xí)mp!
作者:Nakano_May
鏈接:
https://juejin.cn/post/7183739358883610680