I have two tables, Person and Address. The Address has the primary key "id", and this primary key is a foreign key to Person's id. So I woud like to know how to write in jpa to say that the Address's primary id is a foreign key to Person's id. I'm using Postgresql.
Thank you for your answer, but I still trying to do this work. When I try to insert person with the address, hibernate try to insert 0 in the address'id. And this is not the number of the person's id. If I insert just the person is working normal.
I'll show the pojos and my main.
Joined: Jul 14, 2005
You have to set the id of the Address object. Cascading the persist operation to the address causes the address to be persisted, it does cause the object attributes to be updated, etc.
The spec does not specify whether the generated id in Person is present in the object until after the tx commit. I know what Toplink does, but I am not sure what Hibernate does for sequences. You can try putting in code that takes the created person id and assigns it to the address:
Person frederico = new Person(); frederico.setName("frederico");
Address myAddress = new Address(); // *** Set the id *** address.setId(frederico.getId()); myAddress.setStreet("street"); myAddress.setPerson(frederico); frederico.setAddress(myAddress);
If this doesn't work then you will need check your Hibernate forums to see how to eagerly assign the id or to split the creation of the Person and the creation of the Address into two separate transactions.
Oops, typo. It does NOT cause the object attributes to be updated.
And wouldn't that then need to be an embedded object, if the object is a composite object?
Joined: Jul 14, 2005
Originally posted by Mark Spritzler: And wouldn't that then need to be an embedded object, if the object is a composite object?
No, embedded objects do not have PKs. It is an entity that just happens to have the same PK as the object it is associated with. The problem is that he is assuming that the generated PK in one entity is going to be filled in the other related entity that shares the same PK value. I was just explaining that he cannot make this assumption, and that to do it explicitly the originally generated id has to be available before commit.