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.

`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


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.


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


<!– MySQL database driver –>

<!– Hibernate framework –>

<!– Hibernate library dependecy start –>



<!– Hibernate library dependecy end –>


– 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.



  • Then Click Run Button.

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


9) Then create 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.

package com.fndong.user;

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

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

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 and to set join one to one in Annotation setting.


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
public class User implements {

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; = name; = email;

// others attribute getter and setter


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
public class UserDetails implements {
private Integer userDetailId;

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.

<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=”“>validate</property>

<mapping class=”com.fndong.user.User“/>
<mapping class=”com.fndong.user.UserDetails“/>

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

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

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

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

User user = new User(“password“,”Frank FNdong“,”“);
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());



14) we run our project by using “Run application” for our main class – , 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:




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


Leave a Reply

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

You are commenting using your 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