共计 1791 个字符,预计需要花费 5 分钟才能阅读完成。
- mybatis-plus 依赖导入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
倡议应用 3.3.0 后的版本。
导入 mybatis-plus 就不必导入 mybatis 了,抵触!
- 连贯数据库
spring.datasource.username=root
spring.datasource.password=19981204
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl// 配置默认日志
- 设置主键自增
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
应用注解 @TableId(type=IdType.AUTO), 同时将数据库中的 id 字段设置为自增即可。
- 编写配置类来进行主动注入工夫(继承元数据类并重写它的 insertFill 和 updateFill 办法)
应用注解 @TableFiled(fill=FieldFill.INSERT)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
package com.ls.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author dell
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
}
}
正文完
发表至: springboot
2020-07-18