选择依赖和版本
lombok是一个快速生成JAVAbean的一个工具工程和生成日志的工具。未来给我们提供了很大的遍历。
需要在idea中安装插件和pom.xml中进行依赖才可以使用生效:
pom.xml依赖如下:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
复制代码
<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>
复制代码
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>
复制代码
2、准备一个数据库表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;
复制代码
3、配置数据源和mybatis配置
在项目的resource目录下的Application.yaml配置如下:
server:
port: 8080
# 数据源配置
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
复制代码
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);
}
}
复制代码
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;
}
复制代码
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> {
}
复制代码
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> {
}
复制代码
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 {
}
复制代码
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);
// 模拟出现异常,使用条件控制,便于测试结果
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、设置分页
Page page = new Page<>(pageNo,pageSize);
// 2、设置条件
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
// 3、查询分页返回
IPage page1 = userService.page(page, lambdaQueryWrapper);
return new Result(null != page1 ? Code.GET_OK :Code.GET_ERROR,page1);
}
}
复制代码
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
复制代码
@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);
}
}
复制代码
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;
}
复制代码
数据库级别的解决方案
首先将字段设置为timestamp,然后设置不是null,根据当前时间戳更新,在这里注意我们的create_time是不根据当前时间戳更新的!这种方式虽然可以但是不建议!
在mysql低版本的时候可能会出现一个问题,你的sql语句无法导入,而导致这个的原因是有的他只可以设置一个timestamp(在这里提示:mysql5.7 、mysql8.0是可以的!)
具体需要学习mp!
作者:Nakano_May
链接:
https://juejin.cn/post/7183739358883610680