One To One Mapping (Annotation) Example + Maven 3 + Hibernate 4.3.5.Final + MySQL 5.5 + java 8

1) Example on Maven 3 + Hibernate 4.3.5.Final + MySQL 5.5  + java 8,
– Hibernate One to One Mapping Annotation , Here I have user table join with user_details table.

CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
);

CREATE TABLE `user_details` (
`user_detail_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`address` VARCHAR(255),
`poscode` VARCHAR(10),
PRIMARY KEY (`user_detail_id`),
KEY `user_fk` (`user_id`),
CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
);

2) after created, the tables , I’ll show how to create Hibernate One To One Mapping Tutorial (Annotation) project + Maven 3 + Hibernate 4.3.5.Final + MySQL 5.5  + java 8.

3) run maven to create simple app – using command – in command prompt window. ( project name : HibernateAnoOneToOne )
mvn archetype:generate

proj_5_8

4) then open Eclipse Mars, in the left pane eclipse, right click – Import > Import.. > Maven > choose “Existing Maven Project”  > Browse the project that created by maven. > Finish.

proj_5_9

5) Check your pom.xml, add your depenencies jar files below.

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!– Hibernate framework –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>

<!– Hibernate library dependecy start –>
<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>
<!– Hibernate library dependecy end –>

<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>

– when you select Build Automatically, it’ll download all the jars that you stated in pom.xml to local repository.

6) Then add the Hibernate Configuration.
– Before we create the hibernate.cfg.xml your your setting database connection, make sure create the package resource to locate all the resources setting.
– Build Path > Configure Build Path > Source > then – Add Folder.. > Create New Folder .. > put “src\main\resources” > Apply > OK

6.2) create the Hibernate Configuration. Go to Tab “Hibernate Configurations” > + Add Configurations.. , follow the settings below:
– For more details please go to my tutorial on setting Hibernate configurations with database connection settings.

7) Then after done create Hibernate mysql configuration and file hibernate.cfg.xml in “src\main\resources“. I’ll show you how to generate the entity map object
with table from DB mysql.
Project > click on “Hibernate Code Generation Configurations…” > edit the settings like image below.

proj_6_0

proj_4

  • Then Click Run Button.

8) The entities will be created automatically with hbm.xml.

proj_6_1

9) Then create HibernateUtil.java to set the sessionfactory instance.
9.1. Why we need SessionFactory for Hibernate project?

  • Hibernate provides different options to create a SessionFactory instance;
    SessionFactory is used for creating multiple lightweight instances of Session object,
    which in turn enables database operations.
  • We need not worry about the performance side of creating/destroying  those Hibernate Session instances; Because they’re lightweight components.
    more info techpost360 blog.
  • HibernateUtil.java

package com.fndong.user;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

@SuppressWarnings(“deprecation“)
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

10) update the code for User.java and UserDetails.java to set join one to one in Annotation setting.

10.1) User.java

import java.util.Set;
import java.sql.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
* User generated by hbm2java
*/
@Entity
@Table(name=”user“)
public class User implements java.io.Serializable {

@Id
@GeneratedValue
@Column(name=”user_id“)
private Integer userId;

private String password;

private String name;

private String email;

@OneToOne(mappedBy=”user“, cascade=CascadeType.ALL)
private UserDetails userDetails;

public User() {
}

public User(String password, String name, String email) {
this.password = password;
this.name = name;
this.email = email;
}

// others attribute getter and setter

10.2) UserDetails.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

/**
* UserDetails generated by hbm2java
*/
@Entity
@Table(name=”user_details“)
public class UserDetails implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name=”user_detail_id“)
private Integer userDetailId;

@JoinColumn(name=”user_id“)
@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private User user;

private String address;

private String poscode;

public UserDetails() {
}

public UserDetails(User user) {
this.user = user;
}

public UserDetails(String address, String poscode) {
this.address = address;
this.poscode = poscode;
}

public Integer getUserDetailId() {
return this.userDetailId;
}

public void setUserDetailId(Integer userDetailId) {
this.userDetailId = userDetailId;
}

11) REMOVE  Hibernate Mapping (hbm) Files – User.hbm.xml and UserDetails.hbm.xml , The mapping is now defined in Java class as Annotation.

11. Setting your hibernate.cfg.xml , add the mapping class entity.

<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class“>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.password“>P@ssw0rd</property>
<property name=”hibernate.connection.url“>jdbc:mysql://localhost:3306/hibernate</property>
<property name=”hibernate.connection.username“>root</property>
<property name=”hibernate.dialect“>org.hibernate.dialect.MySQLDialect</property>
<property name=”cache.provider_class“>org.hibernate.cache.NoCacheProvider</property>
<property name=”show_sql“>true</property>
<property name=”hbm2ddl.auto“>validate</property>

<mapping class=”com.fndong.user.User“/>
<mapping class=”com.fndong.user.UserDetails“/>
</session-factory>
</hibernate-configuration>

12) Create a main class – App.java, to add function by join two tables.
12.1) App.java

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class App
{
@SuppressWarnings(“unchecked“)
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();

UserDetails userDetails = new UserDetails(“No A419 Cheras Perdana“,”57000“);

User user = new User(“password“,”Frank FNdong“,”fndong@gmail.com“);
user.setUserDetails(userDetails);
userDetails.setUser(user);

session.save(user);
List<User> userlist = session.createQuery(“from User”).list();
for (User user1 : userlist) {
System.out.println(” User and His Details : ” + user1.getName() + ” , ” + user1.getEmail() + “, ” + user1.getUserDetails().getAddress());
}

session.getTransaction().commit();
session.close();

}
}

14) we run our project by using “Run application” for our main class – App.java , make sure the java built Path is JDK, if JRE it will give error message when run.

14.1) Then the result will appeared in your console:

proj_6_2.jpg

 

 

15) Download This Project from my GitHub by click Download button below:

download

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s