Top web site - CHAPTER 7 Advanced entity association mappings User newUser

CHAPTER 7 Advanced entity association mappings User newUser = new User(); Address shippingAddress = new Address(); newUser.setShippingAddress(shippingAddress); session.save(newUser); Hibernate inserts a row into the USERS table and a row into the ADDRESS table. But wait, this doesn t work! How can Hibernate possibly know that the record in the ADDRESS table needs to get the same primary key value as the USERS row? At the beginning of this section, we intentionally didn t show you any primary-key generator in the mapping of Address. You need to enable a special identifier generator. The foreign identifier generator If an Address instance is saved, it needs to get the primary key value of a User object. You can t enable a regular identifier generator, let s say a database sequence. The special foreign identifier generator for Address has to know where to get the right primary key value. The first step to create this identifier binding between Address and User is a bidirectional association. Add a new user property to the Address entity: public class Address { … private User user; // Getters and setters } Map the new user property of an Address in Address.hbm.xml: This mapping not only makes the association bidirectional, but also, with constrained=”true”, adds a foreign key constraint linking the primary key of the ADDRESS table to the primary key of the USERS table. In other words, the database guarantees that an ADDRESS row s primary key references a valid USERS primary key. (As a side effect, Hibernate can now also enable lazy loading of users when a shipping address is loaded. The foreign key constraint means that a user has to exist for a particular shipping address, so a proxy can be enabled without hitting the database. Without this constraint, Hibernate has to hit the database to find out if there is a user for the address; the proxy would then be redundant. We ll come back to this in later chapters.) You can now use the special foreign identifier generator for Address objects:
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.