1:依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--这里不能同时导mybatis包和mybatis-plus的包,会有版本冲突 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2:配置数据源
spring:
datasource:
username: root
password: qwe123456
url: jdbc:mysql://47.115.52.176:3305/mybatis_plus
driver-class-name: com.mysql.jdbc.Driver
3:数据库
create table user
(
id bigint auto_increment comment '主键ID' primary key,
name varchar(30) null comment '姓名',
age int null comment '年龄',
email varchar(50) null comment '邮箱',
create_time datetime default CURRENT_TIMESTAMP null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP comment '更新时间'
);
实体类
4:代码层
实体类
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
/**
* 主键生产策略
* AUTO:主键自增(数据库也要设置自增,不然会报错)
* NONE(1), 未设置主键
* INPUT(2),手动输入 自己配置
* ID_WORKER(3), 默认全局唯一id,雪花算法
* UUID(4), 全局唯一id uuid
* ID_WORKER_STR(5); 字符串表示
*
*/
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private int age;
private String email;
@Version //乐观锁
private Integer version;
@TableLogic //逻辑删除
private int deleted;
//字段添加填充类容
@TableField(fill = FieldFill.INSERT) //插入的时候填充
private LocalDateTime createTime;
//update = "now()"加了乐观锁之后防止自动填充失败的
@TableField(fill = FieldFill.INSERT_UPDATE,update = "now()") //更新的时候填充(最开始是没有数据的,所以用INSERT_UPDATE),
private LocalDateTime updateTime;
}
mapper
UserMapper接口 继承extends BaseMapper< T >
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
5:测试
查询全部
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
结果: