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.
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.
精彩评论