JPA One-to-One Relationship
In this section, you will learn about the one-to-one relationship. In the one-to-one relation mapping a single value association to another entity.
One-to-One: In one-to-one relation, there is one record in Table-A that corresponds to exactly one record in Table-B.
Here we are going to describe the one-to-one relation through an example.
In this relationship, the Address is defined with a one-to-one relationship with annotating the person property in the Address class. The JoinColumn information is also defined. The name attribute defines the foreign key on the table to which the Address class is mapped, and the referenced column defines the primary key to which the Table Person is mapped. Any constraints on the relationship are defined as an attribute to the @OneToOne annotation.
There are two tables: person and address. Both are related to each other through the one-to-one relation. The each person has only one address in this example. Each person has unique id that is referenced to another table address.
You see the following image that represents one-to-one relationship:
You need the following files: Database Table:
- person
- address
<?xml version="1.0" encoding="UTF-8"?> <persistence> <persistence-unit name="default"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>roseindia.Person</class> <class>roseindia.Address</class> <class>roseindia.Parent</class> <class>roseindia.Child</class> <class>roseindia.Author</class> <class>roseindia.Book</class> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://192.168.10.146:3306/hibernateannotation"/> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.password" value="root"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- Echo all executed SQL to stdout --> <property name="hibernate.show_sql" value="true"/> </properties> </persistence-unit> </persistence>
- Person.java
- address.java
- OneToOneRelation.java
Database Table:
person
CREATE TABLE `person` ( `id` int(11) NOT NULL auto_increment, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) |
- address
CREATE TABLE `address` (
`id` int(11) NOT NULL auto_increment,
`address` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
);
Model Class:
- Person.java
/**
*
*/
package roseindia;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Vinod Kumar
*
*/
@Entity
@Table(name="person")
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
@Column(name="name", nullable=false, length=50, insertable=true)
private String name;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
- address.java
/**
*
*/
package roseindia;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
/**
* @author Vinod Kumar
*
*/
@Entity
@Table(name="address")
public class Address implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
@Column(name="address", nullable=false, length=250, insertable=true)
private String address;
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
@OneToOne(cascade=CascadeType.ALL)
private Person person;
/**
* @return the person
*/
public Person getPerson() {
return person;
}
/**
* @param person the person to set
*/
public void setPerson(Person person) {
this.person = person;
}
}
Main Class:
- OneToOneRelation.java
/**
*
*/
package roseindia;
import java.util.HashMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* @author Administrator
*
*/
public class OneToOneRelation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManager em = null;
EntityManagerFactory emf = null;
try {
emf = Persistence.createEntityManagerFactory("default", new HashMap());
em = emf.createEntityManager();
em.getTransaction().begin();
Person per = new Person();
Address add = new Address();
per.setName("Vinod Kumar");
add.setAddress("New Delhi, Sector-3");
add.setPerson(per);
em.persist(add);
em.getTransaction().commit();
System.out.println("Done");
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
em.close();
emf.close();
}
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into person (name) values (?) Hibernate: insert into address (address, person_id) values (?, ?) Done |
Table person:
Table address: