CHAPTER 8 Legacy databases and custom SQL Legacy schemas sometimes have foreign key constraints that don t follow the simple FK references PK rule. Sometimes a foreign key references a nonprimary key: a simple unique column, a natural nonprimary key. Let s assume that in CaveatEmptor, you need to handle a legacy natural key column called CUSTOMER_NR on the USERS table: …
The only thing that is probably new to you in this mapping is the unique attribute. This is one of the SQL customization options in Hibernate; it s not used at runtime (Hibernate doesn t do any uniqueness validation) but to export the database schema with hbm2ddl. If you have an existing schema with a natural key, you assume that it s unique. For completeness, you can and should repeat such important constraints in your mapping metadata maybe you ll use it one day to export a fresh schema. Equivalent to the XML mapping, you can declare a column as unique in JPA annotations: @Column(name = “CUSTOMER_NR”, nullable = false, unique=true) private int customerNr; The next issue you may discover in the legacy schema is that the ITEM table has a foreign key column, SELLER_NR. In an ideal world, you would expect this foreign key to reference the primary key, USER_ID, of the USERS table. However, in a legacy schema, it may reference the natural unique key, CUSTOMER_NR. You need to map it with a property reference: … You ll encounter the property-ref attribute in more exotic Hibernate mappings. It s used to tell Hibernate that this is a mirror of the named property. In the previous example, Hibernate now knows the target of the foreign key reference. One
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.