Hibernate One To Many Annotation Example
Below example will show how to use hibernate advance annotation feature to do ORM mapping to MySQL database and this tutorial is extension of hibernate one-to-many tutorial so please do all environment related setup using this tutorial.
Step 1: Create table in database using below script:
CREATE TABLE mother ( First_Name varchar(50) NULL, Last_Name varchar(25) NULL, City varchar(25) NULL, Zip varchar(25) NULL, State varchar(25) NULL, mother_id int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (mother_id) ) GO CREATE TABLE child ( First_Name varchar(50) NULL, Last_Name varchar(50) NULL, child_id int(11) NOT NULL AUTO_INCREMENT, mother_id int(11) NULL DEFAULT NULL, PRIMARY KEY (child_id), INDEX FK_MOTHER (mother_id), CONSTRAINT FK_MOTHER FOREIGN KEY (mother_id) REFERENCES mother (mother_id) )
Step 2: After you created table in database please generate domain code *.java, *.cfg.xml file by using 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>HibernateOneToManyAnnotation</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>HibernateOneToManyAnnotation 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>HibernateOneToManyAnnotation</finalName> </build> </project>
Step 5: HibernateUtil.java inside com.javahonk.util package:
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() { getSessionFactory().close(); } }
Step 6: hibernate.cfg.xml inside src/main/resource folder and don’t forget to replace your database configuration:
<?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 name="sessionFactory"> <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.Mother" /> <mapping class="com.javahonk.bean.Child" /> </session-factory> </hibernate-configuration>
Step 7: Child.java inside com.javahonk.bean package:
package com.javahonk.bean; // Generated May 22, 2014 2:47:38 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.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Child generated by hbm2java */ @Entity @Table(name = "child", catalog = "javahonk") public class Child implements java.io.Serializable { private Integer childId; private Mother mother; private String firstName; private String lastName; public Child() { } public Child(Mother mother, String firstName, String lastName) { this.mother = mother; this.firstName = firstName; this.lastName = lastName; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "child_id", unique = true, nullable = false) public Integer getChildId() { return this.childId; } public void setChildId(Integer childId) { this.childId = childId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "mother_id") public Mother getMother() { return this.mother; } public void setMother(Mother mother) { this.mother = mother; } @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: Mother.java inside com.javahonk.bean package:
package com.javahonk.bean; // Generated May 22, 2014 2:47:38 PM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; 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.OneToMany; import javax.persistence.Table; /** * Mother generated by hbm2java */ @Entity @Table(name = "mother", catalog = "javahonk") public class Mother implements java.io.Serializable { private Integer motherId; private String firstName; private String lastName; private String city; private String zip; private String state; private Set<Child> childs = new HashSet<Child>(0); public Mother() { } public Mother(String firstName, String lastName, String city, String zip,String state, Set<Child> childs) { this.firstName = firstName; this.lastName = lastName; this.city = city; this.zip = zip; this.state = state; this.childs = childs; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "mother_id", unique = true, nullable = false) public Integer getMotherId() { return this.motherId; } public void setMotherId(Integer motherId) { this.motherId = motherId; } @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 = 25) public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @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; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "mother") public Set<Child> getChilds() { return this.childs; } public void setChilds(Set<Child> childs) { this.childs = childs; } }
Step 9: Main test class: OneToManyInsert.java inside com.javahonk package
package com.javahonk; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.javahonk.bean.Child; import com.javahonk.bean.Mother; import com.javahonk.util.HibernateUtil; public class OneToManyInsert { static SessionFactory sf = HibernateUtil.getSessionFactory(); public static void main(String[] args) { insertData(); selectData(); } private static void selectData() { Session session = sf.openSession(); session.beginTransaction(); List<Mother> moList = session.createQuery("from Mother") .list(); for (Mother mother2 : moList) { System.out.println("Mother table data:"); System.out.println("First Name: "+mother2.getFirstName() +" Last Name: "+mother2.getLastName()+" City: " +mother2.getCity()+" State: "+mother2.getState() +" Zip: "+mother2.getZip()+"\n"); System.out.println("Child table data:"); Set<Child> childs=mother2.getChilds(); for (Iterator<Child> iterator = childs.iterator(); iterator.hasNext();) { Child child3 = (Child) iterator.next(); System.out.println("First Name: " +child3.getFirstName()+" Last name: " +child3.getLastName()+"\n"); } } session.getTransaction().commit(); session.close(); } private static void insertData() { Session session = sf.openSession(); session.beginTransaction(); Mother mother=new Mother(); mother.setFirstName("Mary"); mother.setLastName("Kay"); mother.setCity("Edison"); mother.setZip("10038"); mother.setState("NJ"); session.save(mother); Child child=new Child(); child.setFirstName("Tom"); child.setLastName("Kay"); child.setMother(mother); session.save(child); Child child2=new Child(); child2.setFirstName("John"); child2.setLastName("Kay"); child2.setMother(mother); session.save(child2); session.getTransaction().commit(); session.close(); } }
Step 10: To run — Right click OneToManyInsert.java –> Run As –> Java Application. You will see data inserted into the table and also data retrieved from table that shows on console as below:
Step 11: Below data inserted to table:
Download project: HibernateOneToManyAnnotation
That’s it Hibernate One To Many Annotation Example . For more information read this hibernate tutorial