So I have a CountryRule entity which has an associated Country entity. The association is set up via annotations as
public class CountryRule {
@ManyToOne @JoinColumn(name="country" nullable=false) private Country country;
}
without any cascades, because the Country entity is independent of the CountryRule one. The country table is pretty much static and loaded with default values.
Country rules are created by users through the UI. They have to select a country for the rule. To allow this, UI layer makes a service call to retrieve all the countries via hibernate and displays them in a dropdown the user can select from. The UI layer than passes all the info specified by the user to the service layer and asks it to save the new transient CountryRule entity. This is done by calling countryRuleDAO.saveOrUpdate(countryRule).
When I first made the call, hibernate libraries threw an exception, complaining that a non nullable property was referencing a null or transient object. After reviewing the code, it seemed that when the transient CountryRule object was being persisted, its country field was pointing to the Country object which was transient (not connected to the hibernate session, since it was created anew after returning from UI, even though it still had its id), and because the association was not to be cascaded, the object remained transient, and hibernate couldn't know what to set the country field to. That made sense, and I figured I have to attach the transient Country object to the session somehow (to make hibernate aware of it) before trying to save the CountryRule entity. According to the docs I could find online, either of session.saveOrUpdate or session.merge methods would attach the object, so my code became something like this:
countryDAO.saveOrUpdate(countryRule.getCountry()); countryRuleDAO.save(countryRule);
I also tried some other variotions of this, with merge() and so on, but all my tries resulted in hibernate exceptions:
NonUniqueObject exception or StaleObject exception, mostly complaining that there was more than one object with the same identifier for the Country class in the session. So I am just wondering if I am completely misunderstanding how hibernate works in this regard.
I guess the general form of my question is when you have a situation where you are saving a new object which refers to an already persisted object that you don't need anything done for, but simply want hibernate to know about so that it can set the foreign key fields, what is the general approach? Any help would be appreciated.
|