The Hibernate One-To-One Mapping Example using Foreign key Annotation tutorial shows you how to use Hibernate One-To-One Unidirectional Foreign Key association mapping using annotation based configuration. Here, one table has a foreign key column that references the primary key of associated table.
We are taking an example of Student and Address relationship. This relationship said that a student lives on one Address and one address can be occupied by only one student.
Other interesting posts you may like
Create Database Table
We create two tables with these below scripts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
create table ADDRESS ( id INT(11) NOT NULL AUTO_INCREMENT, street VARCHAR(250) NOT NULL, city VARCHAR(100) NOT NULL, country VARCHAR(100) NOT NULL, PRIMARY KEY (id) ); create table STUDENT ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, entering_date DATE NOT NULL, nationality TEXT NOT NULL, code VARCHAR(30) NOT NULL, address_id INT(11) NOT NULL, PRIMARY KEY (id), CONSTRAINT student_address FOREIGN KEY (address_id) REFERENCES ADDRESS (id) ); |
Noticed that STUDENT table contains a foreign key (here is address_id field) referring to a primary key (here is id field) of ADDRESS table.
Create project directory structure
In this Hibernate One-To-One Mapping Example using Foreign key Annotation tutorial, we will create java project with final directory structure.
Maven dependencies
We provide the required Hibernate and MySQL dependency in pom.xml like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.hibernate</groupId> <artifactId>OneToOneMappingForeignKeyAssociation</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>OneToOneMappingForeignKeyAssociation</name> <properties> <hibernate.version>4.3.11.Final</hibernate.version> <mysql.version>5.1.31</mysql.version> </properties> <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> </project> |
Create Model classes
Model class Student and Address are simple POJO class. Here we are using class Student and Address with JPA annotations to map them to a database tables (these tables were created in above step).
Student Model class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
package com.javabycode.hibernate.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "STUDENT") public class Student implements Serializable { private static final long serialVersionUID = 6832006422622219737L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "NAME", nullable = false) private String name; @Column(name = "ENTERING_DATE", nullable = false) private Date enteringDate; @Column(name = "NATIONALITY", nullable = false) private String nationality; @Column(name = "CODE", nullable = false) private String code; @OneToOne @JoinColumn(name="ADDRESS_ID") private Address address; public Student(){ } public Student(String name, Date enteringDate,String nationality, String code){ this.name = name; this.enteringDate = enteringDate; this.nationality = nationality; this.code = code; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setCode(String code) { this.code = code; } public void setEnteringDate(Date enteringDate) { this.enteringDate = enteringDate; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCode() { return code; } public Date getEnteringDate() { return enteringDate; } public String getNationality() { return nationality; } public void setAddress(Address address) { this.address = address; } public Address getAddress() { return address; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (id != other.id) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", enteringDate=" + enteringDate + ", nationality=" + nationality + ", code=" + code + ", address=" + address +"]"; } } |
Address Model class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package com.javabycode.hibernate.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "ADDRESS") public class Address { @Id @GeneratedValue @Column(name = "ID") private long id; @Column(name = "STREET") private String street; @Column(name = "CITY") private String city; @Column(name = "COUNTRY") private String country; public Address() { } public Address(String street, String city, String country) { this.street = street; this.city = city; this.country = country; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Address [id=" + id + ", street=" + street + ", city=" + city + ", country=" + country + "]"; } } |
Let’s dig deeper:
@OneToOne on address field of Student class indicates that there is a one-to-one association from Student to Address.
We are using @JoinColumn annotation which maps on a seperate column ADDRESS_ID in STUDENT table. Here, You don’t still see the constraint between Student entity and Address entity, do you? Let’s look back the table creation step, you will see the foreign key between Student and ADDRESS table. Thanks to this constraint, the @JoinColumn also point to primary key of ADDRESS table.
Create Hibernate configuration file
We need to provide for hiberate all stuffs like database dialect, driver class, url and account information to connect database. These stuffs is declared in file hibernate.cfg.xml like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">javabycode</property> <property name="hibernate.connection.password">mypassword</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javabycode</property> <property name="show_sql">false</property> <property name="format_sql">false</property> <mapping class="com.javabycode.hibernate.model.Student"/> <mapping class="com.javabycode.hibernate.model.Address"/> </session-factory> </hibernate-configuration> |
This file is placed in src/main/resources folder.
Create Hibernate Utility class
For configuring hibernate on startup and managing session factory we create the HibernateUtil class like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javabycode.hibernate; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static final SessionFactory sessionFactory; private static final ServiceRegistry serviceRegistry; static { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Session Factory could not be created." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } |
Create program to demonstrate Hibernate One-To-One Mapping Example using Foreign key Annotation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.javabycode.hibernate; import java.util.Date; import java.util.List; import org.hibernate.Session; import com.javabycode.hibernate.model.Address; import com.javabycode.hibernate.model.Student; public class HibernateExample { @SuppressWarnings("unchecked") public static void main(String[] args) { Student student = new Student("David Pham", new Date(), "USA", "1234569"); Address address = new Address("LaSalle Street", "Chicago", "USA"); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.persist(address); student.setAddress(address); session.persist(student); session.getTransaction().commit(); session.flush(); List<Student> students = (List<Student>) session.createQuery("from Student ").list(); for (Student s : students) { System.out.println("Student : " + s); } List<Address> addressList = (List<Address>) session.createQuery("from Address ").list(); for (Address add : addressList) { System.out.println("Address : " + add); } session.close(); System.exit(0); } } |
As discussed above, STUDENT table contains the foreign key referring to a primary key of ADDRESS table. So that we have to persisted address entity firstly then we set student’s address property and persist student.
Run main class and we get the output like below:
1 2 |
Student : Student [id=30, name=David Pham, enteringDate=Thu Oct 06 09:22:40 ICT 2016, nationality=USA, code=1234569, address=Address [id=4, street=LaSalle Street, city=Chicago, country=USA]] Address : Address [id=4, street=LaSalle Street, city=Chicago, country=USA] |
That’s it on the Hibernate One-To-One Mapping Example using Foreign key Annotation.
Download complete source code, please hit link below
OneToOneMappingForeignKeyAssociation.zip (304 downloads)
Source code on Github https://github.com/javabycode/hibernate-one-to-one-mapping-example-using-foreign-key-annotation