使用jpa,当前timeStamp不会自动保存到表中

时间:2018-04-10 13:51:07

标签: java postgresql spring-boot jpa

我使用下面的sql查询在postgres DB中创建一个表。

CREATE TABLE IF NOT EXISTS data
(
    id serial, 
    created_at timestamp(0) without time zone DEFAULT (now())::timestamp(0) without time zone,
    created_by integer NOT NULL
);

实体类: -

@Entity
@Table(name = "data")
@Getter
@Setter
public class Data implements Serializable {
    private static final long serialVersionUID = 7462797749946000617L;

    public Data() {
    }

    public Data(Integer createdBy) {
        super();
        this.setCreatedBy(createdBy);
    }

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "created_at")
    private Timestamp createdAt;

    @Column(name = "created_by")
    private Integer createdBy;
}

当我插入数据时,如Date data = new Data(“12312442”);

LogsRepository.save(data);

'created_at'值将在DB中保存为空值。谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用@Column(insertable = false)来强制JPA在生成INSERT语句时忽略该列,以便应用默认的db值。

但是,假设您使用的是弹簧数据,为什么不只是@EnableJpaAuditing,然后使用@CreatedDate注释属性?

请注意,您可以通过createdBy注释并提供@CreatedBy,以类似的方式处理AuditorAware

AuditorAware很好地与Spring Security集成。这是一个示例实现:

@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        return Optional
                    .ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .filter(auth -> !(auth instanceof AnonymousAuthenticationToken))
                .map(Authentication::getPrincipal)
                .map(UserDetails.class::cast)
                .map(UserDetails::getUsername);
    }

}

答案 1 :(得分:0)

对于在数据库图层上填充值的字段,您可以使用Hibernate注释@Generated告诉Hibernate 读取这些值持久化实体之后。在你的情况下:

@Column(name = "created_at")
@Generated(GenerationTime.INSERT)
private Timestamp createdAt;

注意你调用logsRepository.save(data) Hibernate创建两个DB查询:首先 - 插入新数据:

insert into data values(...)

秒 - 读取生成的值:

select created_at from data where id = ...