Hibernate Mappings

转《http://www.alethis.net/reference/db/hibernate.html#Recursive_parent-child_relationship》

1、Primary Key
class Person {
private long personId;
...
}

2、Plain Old Properties
class Person {
...
private String lastName;
...
}

3、Recursive parent-child relationship
class Person {
private int personId;
...
private Person parent;
private Set children;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
PARENT_ID INTEGER;
...
)

...

...

4、Many-to-one relationships
First, with uni-directional navigation
class Person {
private int personId;
...
private Country country;
...
} class Country {
private int countryId;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
COUNTRY_ID INTEGER;
...
) CREATE TABLE COUNTRY (
COUNTRY_ID INTEGER PRIMARY KEY;
...
)

...

...

...

Now, with bi-directional navigation:
class Person {
private int personId;
...
private Country country;
...
} class Country {
private int countryId;
...
private Set citizens;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
COUNTRY_ID INTEGER;
...
) CREATE TABLE COUNTRY (
COUNTRY_ID INTEGER PRIMARY KEY;
...
)

...

...

...

...

5、One-to-one relationships
First, uni-directionally:
class Person {
private int personId;
...
private Address address;
...
} class Address {
private int addressId;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
ADDRESS_ID INTEGER;
...
) CREATE TABLE ADDRESS (
ADDRESS_ID INTEGER PRIMARY KEY;
...
)

...

...

...

Secondly, bi-directionally:
class Person {
private int personId;
...
private Address address;
...
} class Address {
private int addressId;
...
private Person person;
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
ADDRESS_ID INTEGER;
...
) CREATE TABLE ADDRESS (
ADDRESS_ID INTEGER PRIMARY KEY;
...
)

...

...

...

...

6、Many-to-many associations
Requires a join table.
First, uni-directionally:
class Person {
private int personId;
...
} class Project {
private int projectId;
...
private Set participants;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
) CREATE TABLE PROJECT (
PROJECT_ID INTEGER PRIMARY KEY;
...
)
CREATE TABLE PROJECT_PERSON (
PROJECT_ID INTEGER;
PERSON_ID INTEGER;
...
)

...

...

...

How about bi-directional?
class Person {
private int personId;
...
private Set project;
...
} class Project {
private int projectId;
...
private Set participants;
...
}
CREATE TABLE PERSON (
PERSON_ID INTEGER PRIMARY KEY;
...
) CREATE TABLE PROJECT (
PROJECT_ID INTEGER PRIMARY KEY;
...
)
CREATE TABLE PROJECT_PERSON (
PROJECT_ID INTEGER;
PERSON_ID INTEGER;
...
)

...

...

...

...