【问题标题】:JPA @one-to-many // rewrite stored IDJPA @one-to-many // 重写存储的 ID
【发布时间】:2021-06-09 23:20:44
【问题描述】:

我想在写入数据库之前重写 @ManyToOne 关系的存储值,以模仿某些遗留代码的行为。后者将未设置的关系存储为0 而不是null。所有其他值 (>0) 都是常规引用。

有没有办法为@ManyToOne 值实现自定义映射来处理这个问题?

实体:

@Entity
@Table(name = "Content")
public class ContentEntity
    // ..
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "ColorID")
    private ColorEntity color;
}

@Entity
@Table(name = "Color")
public class ColorEntity {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private String id;
    // ..
}

数据库:

    CREATE TABLE `Content` (
        # ..
        `ColorID` VARCHAR(255) DEFAULT NULL);
    CREATE TABLE `Color` (
        `ID` VARCHAR(255) PRIMARY KEY,
        # ..)

目标表中没有id:0对应的条目,但id:>0有多个记录

我在 Spring Boot 应用程序中使用 JPA。

【问题讨论】:

    标签: spring spring-boot hibernate jpa hibernate-mapping


    【解决方案1】:

    我认为您可以为此目的使用柱式转换器:

    @ColumnTransformer(
        forColumn = "ColorID",
        read = "nullif( ColorID, 0 )",
        write = "coalesce( ?, 0 )"
    )
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "ColorID")
    private ColorEntity color;
    

    【讨论】:

    • 这似乎只适用于@Basic 类型。 docs.jboss.org/hibernate/orm/5.3/userguide/html_single/… @ManyToOne 有类似的东西吗?
    • 你是对的,看起来没有办法配置这个。您可以映射基本列和关联,但将关联标记为insertable = false, updatable = false 并使用@JoinFormula(name = "nullif( ColorID, 0 )")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多