Hi All,
I am facing this annoying issue with @OneToOne mapping.
Set up is very simple.
class User {
@OneToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH},mappedBy = "user",fetch=FetchType.EAGER)
private List<UserImage> userImagCollection;
public void addImage(UserImage image) {
if(userImagCollection == null) {
userImagCollection = new ArrayList<UserImage>();
}
image.setUser(this);
userImagCollection.add(image);
}
}
class UserImage {
@TableGenerator(name="tg", table="dw_pk_table",
pkColumnName="name", valueColumnName="value",pkColumnValue="UserImage_id",
allocationSize=10
)
@GeneratedValue(strategy=GenerationType.TABLE, generator="tg")
@Column(name = "id", nullable = false)
private long id;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "userImage")
private Image image;
@JoinColumn(name = "usr_id", referencedColumnName = "usr_id")
@ManyToOne
private User user;
}
class Image
{
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "myForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "myForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value ="userImage")
)
@Column(name = "id", nullable = false)
private long id;
@Lob
@Column(name = "img")
private byte[] img;
@JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
@OneToOne
private UserImage userImage;
}
Simplified veriosn of code.
UserImage userImage = new UserImage();
userImage
UserImage userImage = new UserImage();
userImage.setImage(image);
image.setUserImage(userImage);
user.addImage(userImage);
entitymanger.merge(user)
I think i have wired all the ends.
but merge throws
ed: Db operation failed: Could not update: user: org.hibernate.id.IdentifierGene
rationException: attempted to assign id from null one-to-one property: userImage
: attempted to assign id from null one-to-one property: userImage
I know the reason it is happening ..The reason is userImage object id is null but hibernate should able to handle it. Even if i am creating a new UserImage object , hibernate should get the id from db as per generation strategy and sit in child object (image ) save the data.
In my view that is what the transitive persistance is.
Thanks in advance..
|