Reputation: 13510
Hibernate entities used.
There are Address
and Room
entities and apropriate tables in DB.
Address
can have multiple Room
s.
Both tables have address_Id
and customerEmailAddress
These columns are FK
in Room
table,that references to Address
table.
There is already Address
record in DB.
It's needed to add several Rooms to this
Address.
How to organize Hibernate relation with annotations between Address
and Room
, so Room
table to be updated with appropriate attributes from Address:
address_Id
and customerEmailAddress
Java part looks like:
Room room = new Room();
Address addr = someService.getAddressFromSession();
room.add(addr);
entityManager.persist(room);
Room room2 = new Room();
room2.add(addr);
entityManager.persist(room2);
DB outcome (Room table) should be following:
id||addressId|| customerEmailAddress
1 || 3 || [email protected]
2 || 3 || [email protected]
Upvotes: 0
Views: 108
Reputation: 34367
You haven't mentioned about primary keys of both the tables. Assuming both the tables have their own primary keys,
I think you can have standard mapping done between Address
and Room
objects using component model as below:
Map address_id
and customerEmailAddress
as a component. Refer the documentation for component mapping here-- Hibernate Component Mapping.
Add rooms
in Address
and One-To-Many
relationship using component defined above and set cascade
to All
.
Add address
in Room
as Many-To-One
using component defined above.
Define one addRoom
method in Address
as below(conceptually):
public void addRoom(Room room){
if(this.rooms == null){
this.rooms = new ArrayList<Room>();
}
room.setAddress(this);
this.rooms.add(room);
}
Now you can simply work at Address
level. To save the room
, add the room
to address
and save the address.
Hope this helps!
Upvotes: 1