Hibernate One To One annotation mapping example
This demo will show you how to use hibernate annotation which is enhance feature over using XML configuration to do ORM mapping with database.
- This tutorial is extension of previous tutorial Hibernate One To One Mapping . Please use this tutorial for all environment related settings.
Step 1: Create table database script:
CREATE TABLE address ( Steet_Name varchar(50) NULL, Location varchar(25) NULL, City varchar(25) NULL, Zip varchar(25) NULL, State varchar(25) NULL, id int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id) ) GO CREATE TABLE person ( First_Name varchar(50) NULL, Last_Name varchar(50) NULL, id int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), FOREIGN KEY (id) REFERENCES address (id) )
Step 2: Once you created table in database generate all files using below note:
- We have generated domain code *.java, *.hbm.xml file, *.cfg.xml file from hibernate tools. Please follow this hibernate tutorial to generate all related files
Step 3: Final project structure:
Step 4: pom.xml file:
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <artifactId>HibernateOneToOneAnnotation</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>HibernateOneToOneAnnotation Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- MySQL database --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.6-Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.3.ga</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> </dependencies> <build> <finalName>HibernateOneToOneAnnotation</finalName> </build> </project>
Step 5: HibernateUtil.java file:
package com.javahonk.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new AnnotationConfiguration().configure() .buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory" + " creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
Step 6: hibernate.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">admin</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javahonk</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.search.autoregister_listeners">false</property> <property name="show_sql">true</property> <mapping class="com.javahonk.bean.Person" /> <mapping class="com.javahonk.bean.Address" /> </session-factory> </hibernate-configuration>
Step 7: Person.java class:
package com.javahonk.bean; // Generated May 21, 2014 7:25:48 PM by Hibernate Tools 3.4.0.CR1 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; /** * Person generated by hbm2java */ @Entity @Table(name = "person", catalog = "javahonk") public class Person implements java.io.Serializable { private Integer id; private Address address; private String firstName; private String lastName; public Person() { } public Person(Address address) { this.address = address; } public Person(Address address, String firstName, String lastName) { this.address = address; this.firstName = firstName; this.lastName = lastName; } @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "address")) @Id @GeneratedValue(generator = "generator") @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @OneToOne(fetch = FetchType.LAZY) @PrimaryKeyJoinColumn public Address getAddress() { return this.address; } public void setAddress(Address address) { this.address = address; } @Column(name = "First_Name", length = 50) public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "Last_Name", length = 50) public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
Step 8: Address.java class:
package com.javahonk.bean; // Generated May 21, 2014 7:25:48 PM by Hibernate Tools 3.4.0.CR1 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; /** * Address generated by hbm2java */ @Entity @Table(name = "address", catalog = "javahonk") public class Address implements java.io.Serializable { private Integer id; private String steetName; private String location; private String city; private String zip; private String state; private Person person; public Address() { } public Address(String steetName, String location, String city, String zip, String state, Person person) { this.steetName = steetName; this.location = location; this.city = city; this.zip = zip; this.state = state; this.person = person; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "Steet_Name", length = 50) public String getSteetName() { return this.steetName; } public void setSteetName(String steetName) { this.steetName = steetName; } @Column(name = "Location", length = 25) public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } @Column(name = "City", length = 25) public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } @Column(name = "Zip", length = 25) public String getZip() { return this.zip; } public void setZip(String zip) { this.zip = zip; } @Column(name = "State", length = 25) public String getState() { return this.state; } public void setState(String state) { this.state = state; } @OneToOne(fetch = FetchType.LAZY, mappedBy = "address") public Person getPerson() { return this.person; } public void setPerson(Person person) { this.person = person; } }
Step 9: Main test class: OneToOneInsert.java
package com.javahonk; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.javahonk.bean.Address; import com.javahonk.bean.Person; import com.javahonk.util.HibernateUtil; public class OneToOneInsert { public static void main(String[] args) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); Address address=new Address(); address.setSteetName("Main St."); address.setLocation("NY"); address.setCity("NY"); address.setZip("12345"); address.setState("NY"); Person person=new Person(); person.setFirstName("Java"); person.setLastName("Honk"); person.setAddress(address); address.setPerson(person); session.save(person); List<Address> address3 = session.createQuery("from Address") .list(); for (Address address2 : address3) { System.out.println("Address table data:"); System.out.println("Stree Name: "+address2.getSteetName() +" Location: "+address2.getLocation()+" City: " +address2.getCity()+" State: "+address2.getState() +" Zip: "+address2.getZip()); System.out.println("Person table data:"); System.out.println("First Name: " +address2.getPerson().getFirstName() +" Last name: "+address2.getPerson().getLastName()+"\n"); } session.getTransaction().commit(); session.close(); } }
Step 10: Now run it. To run — right click OneToOneInsert.java –> Run As –> Java Application. You will see data inserted into the table and also it will retrieve inserted data from table and show to the console as below:
Step 11: Below data inserted to the table:
Download project: HibernateOneToOneAnnotation
That’s it Hibernate One To One annotation mapping example . For more information read this hibernate tutorial