Win a copy of Spark in Action this week in the Open Source Projects forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

@OneToMany problem

Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

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?
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
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();

ArrayList < Phone > phoneList = getPhoneList();

for (Phone phone : phoneList) {


it works!!
Everybody's invited. Even this tiny ad:
Thread Boost feature
    Bookmark Topic Watch Topic
  • New Topic