Java Reference
In-Depth Information
<property name="price" column="PRICE"/>
</class>
This mapping specifies that the menuItems field is an ordered list of MenuItem enti-
ties. The <key> element specifies that the foreign key in MENU_ITEM is
RESTAURANT_ID , and the not-null attribute tells Hibernate that the foreign key
cannot be null . It is usually important to specify not-null="true" because other-
wise Hibernate initially will not supply a value for a foreign key such as the
RESTAURANT_ID column, which typically has a NOT NULL constraint. The <index>
element specifies that the column that Hibernate uses to store the position of
MenuItem in the list be called MENU_ITEM_INDEX .
The cascade="all,delete-orphan" attribute specifies that menu items should
be saved or deleted at the same time as the restaurant and that a menu item
should be deleted when it is removed from the menuItems collection. This means,
for example, that the application can construct a restaurant and its menu items
and then save them by calling save() on the restaurant. Hibernate will automati-
cally save the menu items as well. Later, in section 6.1.5, we describe the cascade
attribute in more detail.
Here is the definition of the MENU_ITEM table:
CREATE TABLE MENU_ITEM(
MENU_ITEM_ID NUMBER(10) NOT NULL,
RESTAURANT_ID NUMBER(10) NOT NULL,
MENU_ITEM_INDEX NUMBER(10) NOT NULL,
NAME VARCHAR(50) NOT NULL,
PRICE NUMBER(5, 2) NOT NULL,
)
The MENU_ITEM_ID column is the surrogate primary key and the RESTAURANT_ID
column is a foreign key to the RESTAURANT table.
As you can see, defining the mapping is straightforward. Hibernate will auto-
matically delete a child when either the parent is deleted or the child is removed
from the collection. Furthermore, the child table can be referenced by classes
other than its parent.
But one drawback of using an entity collection is that Hibernate persists a
newly created child using two SQL statements rather than one:
insert
into MENU_ITEM (VERSION, NAME, PRICE, RESTAURANT_ID,
MENU_ITEM_INDEX, MENU_ITEM_ID)
values (?, ?, ?, ?, ?, ?)
update MENU_ITEM
set RESTAURANT_ID=?, MENU_ITEM_INDEX=?
where MENU_ITEM_ID=?
 
 
 
 
 
Search WWH ::




Custom Search