[英]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.