java - Trying to persist an entity with @ManyToOne mapping -


i'm trying persist user has mapping @manytoone userstatus

but when code below, hibernate throws propertyvalueexception

user.setstatus(new userstatus(1)); em.persist(user); // ou session.saveandupdate(user); 

to work have way:

user.setstatus(em.getreference(userstatus.class, 1)); em.persist(user); // ou session.saveandupdate(user); 

i know first way possible, don't know whether need configure or call method (i've tried saveandupdate session , still same)

does have idea?

the error message is:

not-null property references null or transient value 

the mapping

@manytoone(optional = false) @joincolumn(name = "user_status_id", nullable = false) public userstatus getstatus() {     return status; } 

this error means "you referencing null (not persisted) object" , have choice: remove nullable or set @cascade userstatus per persisted when em.persist(user)

@manytoone(optional = false) @joincolumn(name = "user_status_id", nullable = false) @cascade(cascade=cascadetype.all) public userstatus getstatus() {     return status; } 

edit: after various test, using getreference() right way proceed because new userstatus(1) go error , should substituted getreference(userstatus.class,id) return proxied instance of userstatus. proxied object doesn't hit on database, select avoided , field setted on userstatus proxy id, necessary resolve @manytoone relation!

some useful answer: when use entitymanager.find() vs entitymanager.getreference()
what difference between entitymanager.find() , entitymanger.getreference()?


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -