JPA 中 @DynamicInsert 和 @DynamicUpdate 的使用方法

875 阅读1分钟
@Entity
@Data
//@DynamicInsert
@DynamicUpdate
public class Person {



@GeneratedValue(strategy = GenerationType.IDENTITY)
//@Column(columnDefinition = " bigint(20) not null AUTO_INCREMENT", unique = true, updatable = false)
@JsonIgnore
@Id
private Long id;// 数据库自增id,不作为业务对象唯一标识

/**
 * 业务对象全局唯一id
 * ps: 需要在子类中设置uuid为索引, idx_uuid
 */
@Column(length = 32, nullable = false)
private String uuid;

@Column( columnDefinition = "INT default 1")
protected Integer deleteFlag;// 删除标记  1不删除  2删除

@Column(columnDefinition = " datetime NOT NULL DEFAULT CURRENT_TIMESTAMP")
protected Date created;// 创建时间,数据库取当前时间

@Column(columnDefinition = " datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ")
protected Date updated;// 更新时间,数据库自动更新为当前时间,索引更新依赖字段

    @Column(name = "name", nullable = true, length = 20)
    private String name;

    @Column(name = "agee", nullable = true, length = 4)
    private int age;
}

发送请求

image.png 报错

Hibernate: insert into person (created, delete_flag, updated, uuid, agee, name) values (?, ?, ?, ?, ?, ?)
2022-08-11 17:16:29.236  WARN 7112 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2022-08-11 17:16:29.236 ERROR 7112 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'created' cannot be null
2022-08-11 17:16:29.256 ERROR 7112 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

添加上那个注解之后

image.png 成功

也就说这个@DynamicInsert 会自动添加上我们没有写的字段,前提是我们设置好了。

@DynamicUpdate也是一样