IntelliJ Java IDE
The moose likes Object Relational Mapping and the fly likes @OneToMany problem Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Object Relational Mapping
Reply Bookmark "@OneToMany problem" Watch "@OneToMany problem" New topic
Author

@OneToMany problem

Staszek Szychowski
Greenhorn

Joined: Jul 26, 2007
Posts: 2
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

Joined: Jul 14, 2005
Posts: 304
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).


-Mike
Pro JPA 2: Mastering the Java Persistence API
Staszek Szychowski
Greenhorn

Joined: Jul 26, 2007
Posts: 2
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!!
 
 
subject: @OneToMany problem
 
Threads others viewed
Persistence Example
removing all objects on many side of one-to-many relationships
Cascade Type problem
EntityManager persist problem in oneToMany relation
Issue while trying to map extended class
MyEclipse, The Clear Choice

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture