I am trying out the association described in 8.2.1 of the Hibernate 3 manual. I have slightly modified the mapping (see reason below).
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<many-to-one name="address"
column="addressId"
not-null="true"/>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
<property name="fullAddress"/>
</class>
This correctly generates:
create table Address (addressId integer not null auto_increment, fullAddress var
char(255), primary key (addressId))
create table Person (personId integer not null auto_increment, name varchar(255)
, addressId integer not null, primary key (personId))
alter table Person add index FK8E48877552F0AFE3 (addressId), add constraint FK8E
48877552F0AFE3 foreign key (addressId) references Address (addressId)
This is the code that I am using to create the Person and address
Address a = new Address("Church Road London");
Address a1 = new Address("Church Road London");
Person p= new Person();
Person p1= new Person();
p.setName("James");
p.setAddress(a);
p1.setName("Bob");
p1.setAddress(a1);
s.save(p);
s.save(p1);
s.flush();
t.commit();
s.close();
t.commit();
s.close();
This works as well but I have two questions.
1. cascade
Unless I add a cascade attiibute (e.g.cascade="all") to the many to one mapping, the address is not saved. Is that right?
<many-to-one name="Address" column="addressId" cascade="all"
not-null="true"/>
2. unique fullAddress column
The code above works but it creates 2 records in the Address table.
What I really want to do is create one record in the Address table when the fullAddress is the same as the fullAddress of another row and for the addressId in the Person table to use the addressid of that previously created row.
if I change the line of code p1.setAddress(a1) to p1.setAddress(a), it correctly uses the same row because it is the same object. What I want Hibernate to do is to read the address table to see if there is a row with the same fullAddress and use the addressId of that row when saving the person row.
Is there a neat way to do this with Hibernate?
James
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:
Mapping documents:
Code between sessionFactory.openSession() and session.close():
Full stack trace of any exception that occurs:
Name and version of the database you are using:
The generated SQL (show_sql=true):
Debug level Hibernate log excerpt: