Tuesday, February 27, 2007

Hibernate: Annotation many-to-one(foreign-key)

Hibernate Doc (Chap 8.2.1)


::Relationship::
person(many) -> address(one)


::DB Schema::
person( personId, addressId )
address( addressId )


::Java Operation::
person.getAddress();


::Annotation::
@Entity
@Table(name="PERSON")
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToOne
@JoinColumn(name = "ADDRESS_ID")
private Address address;

public Address getAddress() {
return address;
}
}

@Entity
@Table(name="ADDRESS")
public class Address {   

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
}


[Association Mapping List]

5 comments:

Anonymous said...

:) Very nice,
puting the DB Schema along with the java persisted code makes it much more clearer.

The role of each entity and how it is mapped in the relational schema.

Yousif said...

is ADDRESS_ID name of the column in ADDRESS table?

Gvenez said...

no ADDRESS_ID is the name of the column in person table.

born2perform said...

Nice and concise tutorial. I like it.

op cs said...

This is nice, would be great if you can add a pictorial representation to get table relations visibility.