java - Hibernate @ManyToOne violates foreign key constraint -


i have person class contains object title.

public class person {  public person(){     titleid=new title(); }  @id @generatedvalue(strategy = generationtype.auto) private longid;  @manytoone(cascade = {cascadetype.all}, fetch = fetchtype.eager,targetentity=title.class) @joincolumn(name = "titleid", referencedcolumnname = "titleid",columndefinition="int",nullable=false) private title title;  ... ... }  @entity public class title { @generated(generationtime.insert) @column(columndefinition = "serial") private int titleid;  @id private string title; } 

when try insert person object below detail.

  person p=new person();   title t=new title();   t.settitle("mr.");   p.setname("abc");   p.settitle(t);   sessionfactory.getcurrentsession().saveorupdate(p); 

it's working fine , inserting title , person

but when try insert person same title, fails

person p=new person(); title t=new title(); t.settitle("mr."); p.setname("pqr"); p.settitle(t); sessionfactory.getcurrentsession().saveorupdate(p); 

it's giving exception below

org.postgresql.util.psqlexception: error: insert or update on table "person" violates foreign key constraint "fk_9s5vdsvlj3nqy8btf3u1wgvqf" detail: key (titleid)=(0) not present in table "title".

i can pass titleid , work, there chance don't have titleid available.

first have define onetomany relation in title entity below

@entity public class title {    @onetomany(mappedby="title", cascade = cascadetype.all,     orphanremoval=true, fetch=fetchtype.lazy) private list<person> persons = new arraylist<person>(); } 

then add person , title have add person on title persons field.

person p=new person(); p.setname("pqr"); title t=new title(); t.settitle("mr."); t.addpersons(p); p.settitle(t); sessionfactory.getcurrentsession().saveorupdate(t); 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -