簡體   English   中英

休眠一對零或一個映射。 例外:嘗試從空的一對一屬性分配ID?

[英]Hibernate one to zero or one mapping. Exception: attempted to assign id from null one-to-one property?

我就像@Tony在Hibernate中以一到零或一個映射來回答。

我有一個類FileMeta

@Entity
@Inheritance
@DiscriminatorColumn(name = "DISCRIMINATOR", discriminatorType = DiscriminatorType.STRING, length = 30)
@DiscriminatorValue("FileMeta")
public class FileMeta {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected long id;

    ...SOME ATTRIBUTES...

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "FK_GARBAGE")
    @NotFound(action = NotFoundAction.IGNORE)
    protected Garbage garbage;

    @Enumerated(EnumType.ORDINAL)
    private FileT type;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "FK_SHARE")
    @NotFound(action = NotFoundAction.IGNORE)
    private Share share;

    ...METHODS...
}

和一班Share

@Entity
public class Share {
    @Id
    @GeneratedValue(generator = "shareForeignGenerator")
    @GenericGenerator(
            name = "shareForeignGenerator",
            strategy =  "foreign",
            parameters = @Parameter(name = "property", value = "fileMeta")
    )
    private Long id;

    ...SOME ATTRIBUTES...

    @OneToOne(mappedBy = "share")
    @PrimaryKeyJoinColumn
    @NotFound(action = NotFoundAction.IGNORE)
    private FileMeta fileMeta;

    ...METHODS...
}

當我嘗試用Share填充FileMeta時:

    Share share = new Share();
    share.setFileMeta(fileMeta);
    fileMeta.setShare(share);
    fileMetaRepository.save(fileMeta);

我收到異常: attempted to assign id from null one-to-one property

我跟隨進入Hibernate 並注意到,在generator方法中, associatedObject根本不是我給定的Share對象,而是由EventSource實例化的新Share對象

DefaultMergeEventListener.java

    if ( copyCache.containsKey( entity ) ) {
        persister.setIdentifier( copyCache.get( entity ), id, source );
    }
    else {
        ( (MergeContext) copyCache ).put( entity, source.instantiate( persister, id ), true ); //before cascade!
    }

copyCache感知到該entity (即我給定的Share對象)不在copyCache ,並實例化了一個新的Share對象,該對象顯然沒有FileMeta引用。

我完全感到困惑。

該問題的評論中提到了解決方案。 為方便起見,以下給出。

您可以使用@OneToOne(optional = true)或僅使用@OneToOne因為optional默認值為true

如果要強制@OneToOne(optional = false)關系,請指定@OneToOne(optional = false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM