Thursday, March 8, 2007

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

Hibernate Doc (Chap 8.2.2)


::Relationship::
person(one) -> 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)
@Column(name="personId")
private int id;

@OneToOne
@JoinColumn(name="addressId")
private Address address;
}

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

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "addressId")
private int id;
}


[Association Mapping List]

13 comments:

Tim said...

Thanks for this example

Arron said...

+1 ... This worked for me as well. Actually you're cheat sheet references in Hibernate are incredibly useful. Many thanks.

- Arron

Anonymous said...

THANK YOU SO MUCH! i am a newbie at this j2ee stuff, your example was so simple so straight forward, how refreshing, thanks again!

Alfonso said...

Thanks a lot! This is the way I like things: SIMPLE

Anonymous said...

Useful example.

I have a Doubt. When the column names are different then how do u use this onetoone relation. FOr exp.

I m having a table Employee has feeling AddressId and one more Table Addree which had A_Id. A_Id is the Primary key here and AddressId is foreign Key.. THen how to u matych two column Name

Thanks in advance

Anonymous said...

Sorry For lots of spelling mistakes.

Useful example.

I have a Doubt. When the column names are different then how do u use this OnetoOne relation. FOr example.

I m having a table Employee has AddressId field and one more Table Address which has A_Id. A_Id is the Primary key here and AddressId is foreign Key in EMployee table.. THen how to u match two column Names.

Thanks in advance

Anonymous said...

Thanks Tadaya!

spand said...

One table has mapping to many phone numbers table. each phone number has one mapping to table.how do i map it in java jpa3.0. thanks, sonia

spand said...

each facility(table)has 1-many relationship with phone number. each phone number(table) has 1-1 relationship with facility. How do i map it using jpa 3.0 in java classes

Anonymous said...

This will work, but we can insert any record without having appropriate foreign key value in another table....

Visruth CV said...

Thanks........

Sachin Kale said...

Thanks for these articles. But I don't understand how it is a one-to-one relationship. Isn't it one-to-many relationship from Address to Person?

Sandeep Dange said...

how to add one-to-one mapping for the self entity. Like in this example. I want to have parent-child relationship for the Person itself.


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

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="personId")
private int id;

@OneToOne
@JoinColumn()
private Person parentPerson;
}