【问题标题】:JPA + MySQL - column value generated by databaseJPA + MySQL - 数据库生成的列值
【发布时间】:2020-04-02 07:36:40
【问题描述】:

我正在使用 GENERATED ALWAYS AS 公式的列。当我尝试使用 JPA 保存实体值时,我得到了

java.sql.SQLException: The value specified for generated column 'bucket' in table 'discover_cache' is not allowed.

类定义:

@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "discover_cache")
@IdClass(DiscoverCacheId.class)
public class DiscoverCache {

    @Id
    @Column(length = 36)
    private String userId;

    @Id
    private int postId;

    @Column(columnDefinition = "tinyint(4) GENERATED ALWAYS AS (floor(TO_SECONDS(`created_date`) / 900) % 17) STORED NOT NULL")
    @Id
    private short bucket;

    @CreatedDate
    @Column(name = "created_date", updatable = false, columnDefinition = "DATETIME(3)")
    @JsonIgnore
    private Instant createdDate = Instant.now();

    public DiscoverCache(String userId, int postId) {
        this.userId = userId;
        this.postId = postId;
    }
}

@EqualsAndHashCode
@NoArgsConstructor
public class DiscoverCacheId implements Serializable {

    @Column(length = 36)
    private String userId;

    private int postId;

    @Column(columnDefinition = "tinyint(4) GENERATED ALWAYS AS (floor(TO_SECONDS(`created_date`) / 900) % 17) STORED NOT NULL")
    private short bucket;

    public DiscoverCacheId(String userId, int postId, short bucket) {
        this.userId = userId;
        this.postId = postId;
        this.bucket = bucket;
    }
}

如何告诉 JPA 在持久化时忽略此值,以便数据库可以计算我?我当然可以使用本机查询来保存它,但我想使用 JpaRepository

【问题讨论】:

  • 将类型更改为 Short 而不是 short 并且(假设您使用 HIbernate 作为 JPA 提供程序)使用 @DynamicInsert 和/或 @DynamicUpdate 注释您的实体,这会从插入/排除空值/更新语句。

标签: java mysql spring-boot jpa


【解决方案1】:

将可插入和可更新设置为 false。

@Column(name="user_id", nullable = true, insertable = false, updatable = false)
var userId: Long? = null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2015-11-20
    • 2012-11-25
    • 2017-09-21
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    相关资源
    最近更新 更多