Scope of this tutorial is to build the hibernate project using maven, and develop one to many relationship with two entities.
For example: Bank and Customer, one bank has many customers.
Prerequisite:
- jdk 1.6 or above
- Latest Maven ( if you want to know more about installation visit this article “Maven Tutorial”.
- MySql 5.1 or above
- Before starting create a database ormtestdb.
- Create hibernate example project using maven command line.
[code lang=”plain”]mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.javavapor.example.hibernate -DartifactId=HibernateTestExample -Dversion=1.0.0[/code]
- Update POM.xml file by adding dependency.
[code lang=”xml”]
<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.javavapor.examples.hibernate</groupId>
<artifactId>HibernateTestExample</artifactId>
<packaging>jar</packaging>
<version>1.0.0</version>
<name>HibernateTestExample</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
[/code]
- Create domain model entities.
[code lang=”java”] /*Bank Entity realtionship with Customer Entity :one to many */
package com.javavapor.example.hibernate.domainmodel;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
@Entity
@Table
public class Bank {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy=&quot;bank&quot;,cascade=CascadeType.PERSIST)
private List&lt;Customer&gt; customers = new ArrayList&lt;Customer&gt;();
public Bank() {
super();
}
public Bank(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List&lt;Customer&gt; getCustomers() {
return customers;
}
public void setCustomers(List&lt;Customer&gt; customers) {
this.customers = customers;
}
}[/code]
Creating Customer.java
[code lang=”java”]/*Customer Entity realtionship with Bank*/
package com.javavapor.example.hibernate.domainmodel;
import javax.persistence.*;
@Entity
@Table
public class Customer {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
private Bank bank;
public Customer() {}
public Customer(String name, Bank bank ) {
this.name = name;
this.bank = bank;
}
public Customer(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
@Override
public String toString() {
return &quot;Customer [id=&quot; + id
+ &quot;, name=&quot; + name
+ &quot;, bank=&quot; + bank.getName() + &quot;]&quot;;
}
} [/code]
- Add Util class
[code lang=”java”]package com.javavapor.example.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateOrmUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the new SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
} [/code]
- Create test class
[code lang=”java”]package com.javavapor.example.hibernate;
import java.util.List;
import com.javavapor.example.hibernate.domainmodel.Customer;
import com.javavapor.example.hibernate.domainmodel.Bank;
import com.javavapor.example.hibernate.util.*;
import org.hibernate.*;
public class HibernateOrmTest {
public static void main(String[] args) {
Session session = HibernateOrmUtil.getSessionFactory().openSession();
session.beginTransaction();
Bank bank = new Bank(&quot;ABC World Ltd.&quot;);
session.save(bank);
session.save(new Customer(&quot;Tom Cruise&quot;,bank));
session.save(new Customer(&quot;Kim Kardashian&quot;,bank));
session.getTransaction().commit();
Query query = session.createQuery(&quot;From Customer &quot;);
List&lt;Customer&gt; resultList = query.list();
System.out.println(&quot;No. of Customer:&quot; + resultList.size());
for (Customer next : resultList) {
System.out.println(&quot;next Customer: &quot; + next);
}
}
} [/code]
- Add hibernate.cfg.xml to srcmainresource folder
[code lang=”xml”]
<?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="connection.url">jdbc:mysql://localhost:3306/ormtestdb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.javavapor.example.hibernate.domainmodel.Customer" />
<mapping class="com.javavapor.example.hibernate.domainmodel.Bank" />
</session-factory>
</hibernate-configuration>
[/code]
- Finally test your project
[code lang=”plain”] mvn compile exec:java -Dexec.mainClass=com.javavapor.example.hibernate.HibernateOrmTest[/code]