gpt4 book ai didi

java - JPA + MySQL - 数据库生成的列值

转载 作者:行者123 更新时间:2023-12-04 04:21:17 25 4
gpt4 key购买 nike

我正在使用带有 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 在持久化时忽略这个值,以便我可以被数据库计算?我当然可以使用 native 查询来保存它,但我想使用 JpaRepository<>

最佳答案

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

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

关于java - JPA + MySQL - 数据库生成的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com