Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Persisting a class to two tables with Hibernate

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,

I have 2 tables, named �items� and �item_types� (a lookup table), in which I�ve included the SQL DDL. I want to map them to a class defined below. I�ve included the mapping I�ve used which works great for querying the data. However, I�d like to save the data as well. I couldn�t figure out how to make Hibernate aware of the sequence in the item_types look-up table joined to my main table. I�m working with a legacy database and legacy class system, so I cannot easily create classes for each table.

I�d like to instantiate a class, assign a value to the classes types property and have it persist to the item table with the correct foreign key. Ideally, if a new �item_types.type� is added, it would get the next sequence value, insert the new type into item_types, and insert the new item with the correct foreign key for the new item type.

I assume I need to use the <join> tag, but I couldn�t figure out how to make it aware of my sequence.

Here's my mapping:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Item" table="items">
<id name="id" column="id">
<generator class="sequence">
<param name="sequence">types_sequence</param>
</generator>
</id>
<property name="prop1" column="prop1"/>
<property name="prop2" column="prop2"/>
<join table="item_types">
<key column="type_id"/>
<property name="type" column="type"/>
</join>
</class>
</hibernate-mapping>


Here's my tables:
create table items(
id int primary key,
prop1 varchar2(50),
prop2 varchar2(50),
...
item_type int references item_types(type_id)
);

create table item_types(
type_id int primary key,
type varchar(25)
);

Here's my class:
public class Item{
int id;
String prop1;
String prop2;
String type;
}


I'm using Hibernate 3 on Oracle10g.

Thanks in advance
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic