Guys ,
I posted one question but no body answered my question and i guess i know the reason ( I think it was length of my post and all the code i wrote in that post :)) ). So this time i m going to frame my question differently.
Ok..here i go (Please have patience i am a hibernate newbie)
I am trying to add a grandchild to an object and while doing that i also have to create child of that object. Cascade.All is mentioned in all three classes . So my question is hibernate should be able to generate id for child and then grand child and persist the whole graph..right ? as per transitive persistance..
Here is what is happening... hibernate does not generate id for child untill the end of transaction and grandchild does not get that id so whole transaction fails with
Caused by: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property: userImage
However if i split this operation into two parts first i save (UserImage) commit the tx and then in another tx save image it works like charm.
Here is the code snippet
Code:
User UserImage and Image
User {
collection<UserImage> userimageCollection ;
@OneToMany(cascade = {CascadeType.ALL},mappedBy = "user",fetch=FetchType.EAGER)
private List<UserImage> userImagCollection;
public void addUserImage(UserImage) {
userimageCollection.add(userImage);
userImage.add(user);
}
}
UserImage {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="tg")
@Column(name = "id", nullable = false)
private long id;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "userImage")
private Image image;
}
Image {
@Id
@GeneratedValue(generator = "myForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "myForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value ="userImage")
)
@JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
@OneToOne
private UserImage userImage;
@Lob
@Column(name = "img")
private byte[] img;
}
To add one image in db I do following
@Transactional
updateUser{
UserImage userImage = new UserImage();
Image image = {get from front end completely populated "New" image object}
userImage.setImage(image);
image.setUserImage(userImage)
User user= getFromDb();
user.addUserImage(userImage);
}
[/code]