Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring JPA@one-to-many//重写存储的ID_Spring_Spring Boot_Hibernate_Jpa_Hibernate Mapping - Fatal编程技术网

Spring JPA@one-to-many//重写存储的ID

Spring JPA@one-to-many//重写存储的ID,spring,spring-boot,hibernate,jpa,hibernate-mapping,Spring,Spring Boot,Hibernate,Jpa,Hibernate Mapping,在写入数据库之前,我想重写@manytone关系的存储值,以模拟某些遗留代码的行为。后者将未设置的关系存储为0,而不是null。所有其他值(>0)都是常规引用 有没有办法实现@ManyToOne值的自定义映射来处理此问题 实体: @Entity @Table(name = "Content") public class ContentEntity // .. @ManyToOne(fetch = FetchType.EAGER) @JoinColumn

在写入数据库之前,我想重写
@manytone
关系的存储值,以模拟某些遗留代码的行为。后者将未设置的关系存储为
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,
        # ..)
数据库:

@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。

我认为您可以使用列转换器来实现此目的:

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

这似乎只适用于
@Basic
类型。对于
@ManyToOne
,是否有类似的功能?您是对的,似乎无法配置此功能。您可以映射基本列和关联,但可以将关联标记为
insertable=false,updateable=false
,并使用
@JoinFormula(name=“nullif(ColorID,0)”)