tags:

views:

23

answers:

1

Think 2 entities OneToOne mapped. Person and Car. A Person can have a Car.

We have a Person object loaded from database. I want to change Person's Car. The problem is I don't have a loaded Car object to use. Instead I only have Car's ID. Using this Car Id , is it possible to set Person's Car to that wanted Car (which we have it's id), without loading/selecting any Car from DB ? And than save this Person and it's car to db. I don't need any information fetched about. I only need to tell Hibernate that I want Person's Car to be the Car which has that Id.

Is this possible? Sorry If my English sux. Thanks in advice.

A: 

That depends on how your association is mapped.

Assuming it's mapped via foreign key (from Person to Car) AND you're sure that the "new" car instance actually exists, you can use Session.load() method to return a persistent proxy of new Car entity, then set that on Person and save Person. Car should not actually be loaded as long as association is not fetched eagerly:

Person person = ...;
Car newCar = session.load(Car.class, newCarId);
person.setCar(newCar);
session.saveOrUpdate(person);

If your association is mapped via primary keys, setting a new car is impossible to begin with.

On a side note, Person to Car is technically a one-to-many (Person = owner) or many-to-many (Person = driver) relationship rather than one-to-one.

ChssPly76
Thanks for answer. I agree with you about one-to-many relation. But Person and Car example is easy to explain.What is the situation if code run at remote client/outofsession? ıs it possible without .load()? Anything to surrogate the car or it's proxy with only id while no session avaible nor a remote call? Than we send our object to the server and saveOrUpdate(person) =) .
Ginnun
Remote API is a different matter. Several possible options are: (1) Have remote client call your API to retrieve new car instance and set it; (2) expose "changeCarOnPerson(Person, NewCarId)" through your API; (3) either write a CarProxy class (assuming your API allows) or allow client to create a Car instance with ID only, set that on Person, have your service load the actual Car instance. I've got to say that option #1 is **by far** the cleanest.
ChssPly76
Thanks for the answers. Those are what I thought exactly.
Ginnun