Hibernate Query Language – HQL

Hibernate Query Language – HQL  :

Description about HQL :-

  • HQL is the Object Oriented query language for Hibernate Framework.
  • HQL is a case-sensitive.
  • HQL with a simple and easy-to-use language.
    • While SQL use “SELECT * FROM USERS” to fetch all records in USERS table, But
    • for HQL we use “FROM USERS” .

1.) HQL Insert Query Language.

  • HQL also support INSERT INTO – example:
  • In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table.
    • Query query = session.createQuery(“INSERT into USERS(userId, username)” + “SELECT bk.userId,bk.username FROM  BK_USERS bk“);

2.) HQL Update Query Language.

  • Example of HQL update query
 Transaction trans =session.beginTransaction();  
    Query query=session.createQuery("update Patient set PatientName=:pname where id=:pid");  
    query.setParameter("pname","franko Nando");  
    query.setParameter("pid",01);  
      
    int status=query.executeUpdate();  
    System.out.println(status);  
    trans.commit();

 

notes – hibernate ORM Q & A part 1

> Notes – hibernate ORM Q & A

  1. Error on HQL – [Ljava.lang.Object; cannot be cast to com.fndong.entities.Users ?
 private static final String HQL_SELECT_USERS ="select u.uid , u.username,
 u.password from Users u";

public void getUsers(){
List<Users> list = null;
Query query = session.createQuery(HQL_SELECT_USERS);
list = (List<Users>)query.list();
 for(Users h: list){
                    System.out.println("username: " + h.getUsername());
                 }
}

Errors: Ljava.lang.Object; cannot be cast to com.fndong.entities.Users

1.1.) Solutions on Question No. 1 :

You are selecting u.username(which looks like a String), but you are trying to cast that String to your Bean class (Users.java). If you execute an HQL query with a single field, the returned list will contain objects of the type of that field, you are getting a list of String objects.

> If you want to select Bean objects, your query should look like this : CORRECT WAY if we want to cast with Bean

 private static final String HQL_SELECT_USERS ="select u from Users u";

Hibernate Project + maven 3 + Jetty 9.3 Web Server – My study Notes

  1. Create Simple Project – using eclipse IDE.
  2. At Command Prompt , run the maven script to create example Dynamic Web Project:
  • mvn archetype:generate -DgroupId=com.fndong -DartifactId=JettyHibernate -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

hibertnate.png

3. Then, import project to your Eclipse IDE , using “Existing Maven Projects” .Setting up and fix if its have an errors.

4. add the jetty Maven Plugin add inside pom.xml , so i can use jetty web server for running my simple application.

<!– https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin –>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.3.10.v20160621</version>
</dependency>

4.2. And also servlet

<!– Servlet Library –>
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
</dependency>

5. pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
  xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”&gt;
  <modelVersion>4.0.0</modelVersion>
 <groupId>com.fndong</groupId>
  <artifactId>JettyHibernate</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>HibernateJetty Maven Webapp</name>
  <url>http://maven.apache.org</url&gt;
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!– https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin –>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.3.10.v20160621</version>
</dependency>
  </dependencies>
   <build>
        <finalName>JettyHibernate</finalName>
        <plugins>
             
            <!– http://mvnrepository.com/artifact/org.eclipse.jetty/jetty-maven-plugin –>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.3.10.v20160621</version>
                 
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <webApp>
                        <contextPath>/JettyHibernate</contextPath>
                    </webApp>
                </configuration>
                 
            </plugin>
        </plugins>
    </build>
</project>

6. Run Configurations… at eclipse IDE.

 

7. Add New Maven Build for Jetty running program.

mavenbuild

  • Apply and Run

jettyrun.jpg

8. Errors after running the command:

Exception in thread “main” java.util.ServiceConfigurationError: org.apache.juli.logging.Log: Provider org.eclipse.jetty.apache.jsp.JuliLog not a subtype
    at java.util.ServiceLoader.fail(ServiceLoader.java:239)

9. If you guys read that error, can you guys help me to solve it. why jetty command in run configuration Eclipse IDE does not run.

10. I’ll continue using command prompt to run it.

  • Run command jetty : mvn package jetty:run

serverstarted.jpg

 11. Output my web in browser – http://localhost:8080/JettyHibernate/:

successhelloworld.jpg

12. Maybe my eclipse setting have problem, my command prompt work fine.

13. I’ll Ignore with jetty run on eclipse , I just using directly run on command prompt – mvn package jetty:run.

14. Continue integrate with Facade Design Pattern + Hibernate ORM + mysql

 

 

Example – Simple Hibernate Application + maven + mysql

Example – Simple Hibernate Application.

1.) Create the java project – “SimpleHibernateApp

  • New > Java Project > <Project name – SimpleHibernateApp> > next > Finnish.
  • convert to Maven Project – Configure > Convert to Maven Project

2.) Add jar files from maven dependencies in POM.xml

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

mven_dependency_3.jpg

  • Diagram for maven dependencies.

3.) Create the Persistent class

  • Set the main source in built path for java –  “src/main/java” and resources – “src/main/resources“.

Create the persistent class – User.java , Right click on src/main/java > New > Class – specify the class with package name (e.g. com.fndong.user) – finish.

package com.fndong.user;

import java.util.HashSet;
import java.util.Set;

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

public class User implements java.io.Serializable {

private Integer userId;
private String password;
private String name;
private String email;

public User() {
}

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

 

// Set your Getter and Setter

}

4.) Create the mapping file for Persistent class in  com/main/resources

com.fndong.user.User.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd“>
<!– Generated Mar 11, 2016 2:47:24 PM by Hibernate Tools 4.3.1.Final –>
<hibernate-mapping>
<class name=”com.fndong.user.User” table=”user” catalog=”hibernate” optimistic-lock=”version“>

<id name=”userId” type=”java.lang.Integer“>
<column name=”user_id” />
<generator class=”identity” />
</id>
<one-to-one name=”userDetails” class=”com.fndong.user.UserDetails
cascade=”save-update”></one-to-one>

<property name=”password” type=”string“>
<column name=”password” not-null=”true” />
</property>

<property name=”name” type=”string“>
<column name=”name” not-null=”true” />

</property>
<property name=”email” type=”string“>
<column name=”email” not-null=”true” />
</property>
</class>

</hibernate-mapping>

5.) Create the Configuration file – com.fndong.user. hibernate.cfg.xml

  • The configuration file contains all the informations for the database such as jdbc connection_url, mysql_driver_class, username, password, and mapping class for User.java and UserDetail.java .
  • The hbm2ddl.auto property is used to create the table in the database automatically.
  • To create the configuration file, right click on src/main/resources > new > com.fndong.user > file and create your file name – hibernate.cfg.xml.

<!DOCTYPE hibernate-configuration PUBLIC
-//Hibernate/Hibernate Configuration DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd“>
<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“/>
</session-factory>
</hibernate-configuration>

hibernate_1

 

6.) Create the class that retrieve or store the persistent object.

  • Create a simple class – call Retrieve.java inside package “com.fndong.user” for storing the User object to the database.

com.fndong.user.Retrieve.java 

package com.fndong.user;

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

public class Retrieve {
public static void main(String[] args) {

//creating configuration object
Configuration cfg=new Configuration();
cfg.configure(“hibernate.cfg.xml“);//populates the data of the configuration file

//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();

//creating session object
Session session=factory.openSession();

//creating transaction object
Transaction trans=session.beginTransaction();

User user =new User();
user.setUserId(1);
user.setName(“Franko“);
user.setEmail(“Frankey“);
user.setPassword(“P@ssw0rd“);

//persisting the object
session.merge(user);

//transaction is committed
trans.commit();
session.close();

System.out.println(“successfully created“);

}
}

7.) My Fully structure Project.

proj_struc_hibernate.jpg

8.) Run the application – Retrive.java ( its a main class) – right click class and run > Java Application.

  • Result:

suucess_1.jpg

8. Some constraint and an error with solution:

  • Error: Exception in thread “main” org.hibernate.PersistentObjectException: detached entity passed to persist: com.fndong.user.User
  • Solution: It seems like persist function causes problem, so some solution to use method .merge() as a insert record.

User user =new User();
user.setUserId(1);
user.setName(“Franko“);
user.setEmail(“Frankey“);
user.setPassword(“P@ssw0rd“);

//persisting the object
session.merge(user);

9.) If You Guys want to Download the Source Code. Click Download button Below:

download

 

Spring MVC 4 + Hibernate 4.3.5.Final (Annotation) + JPA + MySql 5.5 – Example Project

1) Example on Maven 3 + Spring 4 (Spring MVC) + Hibernate 4.3.5.Final (Annotation) + JPA + MySQL 5.5  + java 8.

architecture_springMVC_hibernate_JPA_mysql.jpg

Architecture diagram above, is between Spring MVC + Hibernate + JPA + Mysql 5.5

1.1) For this example project , it used Data Access Object Pattern or DAO pattern in Domain layer.

1.2)  Based on Architecture diagram above, in JPA box, I used Hibernate ORM to integrate between table database.

  • Create table ‘user‘ and table ‘user_details‘, One-To-One Join 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`)
);

open CMD , and your folder  project , add this command and Enter :

mvn archetype:generate -DgroupId=<Your domain name> -DartifactId=<Project Name> -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

  • My Example: mvn archetype:generate -DgroupId=com.fndong -DartifactId=SpringMVCProjOne -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
  • If you check the result is : Build Success , its mean you are successfully create new web app project using maven.

2.) Then , Import the SpringMVCProjOne  maven project to your Eclipse Mars.

2.1) after importing , check your Build Path , some folder java are missing “src\main\java” and “src\test\java” , remove the missing , and Add new “Add Folder..” , create the two missing folder.

3) Check your pom.xml, add your dependencies jar files below:

Add Spring 4 + Hibernate 4.3.5.Final dependency in pom.xml.

  <properties>
<spring.version>4.0.1.RELEASE</spring.version>
<jdk.version>1.8</jdk.version>
<hib.version>4.3.5.Final</hib.version>
</properties>

<dependencies>

<!– Spring dependencies –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</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> ${hib.version}</version>
</dependency>

4) Then , check Maven Dependency in Web Deployment Assembly.

maven-depency_2.jpg

5.) For creating an entities , i’ll using generate entities using JPA.

5.1) If you creating an entity ,it doesn’t view the database connection , please make sure you enable JPA . ( for newbies – create JPA Project)

jpalink_2.jpg

  • the libraries in jpaLinkEclise :

jpaLink_4

 

5.2.) create package for entity “com.fndong.user.entities“, and add your User table and User_detail table Entity.

5.2.1.) Right-click the SpringMVCProjOne  project in the Project Explorer and select NEW > JPA Entities from Tables.

jpa_entities.jpg

  • unchecked the List generate classes in persistence.xml ( Because we will using Spring Autowired )

5.3.) Then , it will automatically generate classes entities User and User_details.

jpa_enties2.jpg

5.4.) User.java entity in “com.fndong.user.entities” :

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
@Entity
@NamedQuery(name=”User.findAll“, query=”SELECT u FROM User u“)
public class User implements Serializable {
private static final long serialVersionUID = 1L;

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

private String email;

private String name;

private String password;

//bi-directional many-to-one association to UserDetail
@OneToMany(mappedBy=”user“)
private List<UserDetail> userDetails;

public User() {
}

// getter and Setter …….

5.5.) UserDetail.java entity in “com.fndong.user.entities” :

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name=”user_details“)
@NamedQuery(name=”UserDetail.findAll“, query=”SELECT u FROM UserDetail u“)
public class UserDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name=”user_detail_id“)
private int userDetailId;

private String address;

private String poscode;

//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name=”user_id“)
private User user;

// getter and Setter …….

  • JPALink Plugin will automatically set for the tables that have join – one to Many.

@ManyToOne
@JoinColumn(name=”user_id“)
private User user;

  • JPA API that we have been use such as :
  • @Id annotation
  • @Collumn annotation
  • @JoinColumn annotation
  • @Table annotation
  • @NamedQuery annotation
  • @Entity annotation

 

6.0.) Create the DAO Interface and DAO Implementation “com.fndong.user.Dao” :

6.1.) Create User entity DAO Interface  in “com.fndong.user.Dao” , NEW > Interface > Name – UserDao > Finish .

package com.fndong.user.dao;

import com.fndong.user.entities.User;

public interface UserDao {
// Get / Search
public User getUserDatabyName(String username);

// create
public int create(User user);

// edit
public int updateUser(User user);
}

  • Dao Interface for User – UserDao.java, i have add Three Functions , 1. Search – getUserDatabyName(String username) 2. Add- Create(User user) , Edit – UpdateUser(User user).

6.2.) Create Dao Implementation where your you will add HQL – Hibernate SQL , This class is responsible to get data from a data source which can be database – UserDaoImpl.java.

createDaoImp;l.jpg

  • Above diagram is how you can add the interface UserDao for creating Dao Implementation – UserDaoImpl.java.

package com.fndong.user.dao;

import com.fndong.user.entities.User;

public class UserDaoImpl implements UserDao {

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#getUserDatabyName(java.lang.String)
*/
@Override
public User getUserDatabyName(String username) {
// TODO Auto-generated method stub
return null;
}

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#create(com.fndong.user.entities.User)
*/
@Override
public int create(User user) {
// TODO Auto-generated method stub
return 0;
}

/* (non-Javadoc)
* @see com.fndong.user.dao.UserDao#updateUser(com.fndong.user.entities.User)
*/
@Override
public int updateUser(User user) {
// TODO Auto-generated method stub
return 0;
}

  • Above Dao Implemention automatically created method from Dao Interface.

7.) Lets creating Hibernate.cfg.xml in package – /src/main/resources (Hibernate ORM Mapping database – Annotation )

<?xml version=”1.0” encoding=”UTF-8“?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd“>
<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.entities.User“/>
<mapping class=”com.fndong.user.entities.UserDetails“/>
</session-factory>
</hibernate-configuration>

cfg.jpg

8.) Create Hibernate SessionFactory class – HibernateUtil.java in new package “com.fndong.util“.

package com.fndong.util;

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;
}
}

9. Create Service layer …. to be continued

 

 

 

 

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

Explanation on Hibernate – inverse=”false” lazy=”true” fetch=”select” – (Many To Many Relationship )

Explanation on Hibernateinverse=”falselazy=”truefetch=”select” – (Many To Many Relationship )

Hibernate Mapping XML (hbm)
Following are the hibernate mapping files for each enitity Role and Transactions.

1) Role.hbm.xml

<hibernate-mapping>
<class name=”com.fndong.customer.Role” table=”role” catalog=”hibernate” optimistic-lock=”version”>
<id name=”roleId” type=”java.lang.Integer“>
<column name=”role_id” />
<generator class=”identity” />
</id>
<property name=”roleName” type=”string“>
<column name=”role_name” length=”30” not-null=”true” />
</property>
<set name=”transactionses” table=”trans_role” inverse=”false” lazy=”true” fetch=”select” cascade=”all“>
<key>
<column name=”role_id” not-null=”true” />
</key>
<many-to-many entity-name=”com.fndong.customer.Transactions”>
<column name=”transaction_id” not-null=”true” />
</many-to-many>
</set>
</class>
</hibernate-mapping>

2) Transactions.hbm.xml

<hibernate-mapping>
<class name=”com.fndong.customer.Transactions” table=”transactions” catalog=”hibernate” optimistic-lock=”version“>
<id name=”transactionId” type=”java.lang.Integer“>
<column name=”transaction_id” />
<generator class=”identity” />
</id>
<property name=”transactionName” type=”string“>
<column name=”transaction_name” length=”30” not-null=”true” />
</property>
<set name=”roles” table=”trans_role” inverse=”true” lazy=”true” fetch=”select“>
<key>
<column name=”transaction_id” not-null=”true” />
</key>
<many-to-many entity-name=”com.fndong.customer.Role“>
<column name=”role_id” not-null=”true” />
</many-to-many>
</set>
</class>
</hibernate-mapping>

9.3) Explanations on “<set name=”transactionses” table=”trans_role” inverse=”false” lazy=”true” fetch=”select” cascade=”all“>

  • inverse=”false” =  Meaning : Inverse Attribute present in Many-to-Many and One To-Many relationship, and denotes which side is responsible  for the relationship. 
    • inverse = “true”– It defines which side is responsible to take care the relationship.
    • for value “false” – which means both sides are the owner of the relationship. In Hibernate, it will enable two sides to update the foreign key in composite table – trans_roles.
  • lazy=”true attribute , Meaning : “true” value , is enable lazy loading of the parent and child collections.
    • what is lazy loading ?
      • Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class.  Lazy = true (means not to load child)
      • lazy=false, and hibernate will load the child when parent is loaded from the database.
      • More info on lazy loading… more info:
  • fetch=”select” – Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.