• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

@OneToMany problem

 
Staszek Szychowski
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have quite irritating problem with onetomany relationship in my app.

Lets say that I have 2 entities: Person and Phone. Both have id's generated by sequence in DB (Postgresql 8.2). Of cource one Person can have many Phones

So I do relation as follows:

in Person:

@OneToMany(mappedBy="owner", cascade={CascadeType.ALL})
private Collection < Phone > phones;

in Phone

@ManyToOne
@JoinColumn(name="person_id")
private Person owner;

If I try to create a new Person, and then assign to it collection of new Phones it fails to execute persist method from entity manager.

Application server log says that I try to execute sql that is saving Phone without Person id. Since foreign key in phone is restricted to be not null it must fail. What do I wrong?
 
Mike Keith
author
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have the following two annotations on each of the identifier attributes?

@Id @GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, make sure that you are either generating the schema, or using a generator that you ahve defined (and including the generator attribute in the @GeneratedValue annotation).
 
Staszek Szychowski
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did it. Actually it works great if I save Person entity withour any phone. Id is correctly assigned. Moreover, if is do something like this:

Pesion peron = new Person();
em.persist(person);

ArrayList < Phone > phoneList = getPhoneList();

for (Phone phone : phoneList) {
phone.setOwner(person);
}

person.setPhones(phoneList);

it works!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic