Site icon NgDeveloper

How to set up Java Hibernate with MySQL in Eclipse ?

How to set up Java Hibernate with MySQL in Eclipse - featured image

Hibernate+MySQL+Java+Eclipse: How ?

Today we are going to see how to integrate Hibernate with mysql in Java using Eclipse.

PreRequisite:

1. Ensure you have Eclipse Juno [you can also have some other version of eclipse, but we installed hibernate tools in eclipse Juno only. I would recommend you to download eclipse juno to install hibernate tools].

2. Hibernate tools installed in Eclipse Juno[not mandatory, but it’s recommended to use HQL in eclipse itself].

If you do not know which version of eclipse to download and how to install hibernate tools in eclipse, you can learn from here.

Installing Hibernate tools in Eclipse Juno

Hibernate 4 Required Jars with MySQL connector Jar

Now we have completed setting up eclipse juno with hibernate tools and hibernate 4 jars with mysql connector Jar.

It’s time to create first java hibernate program with MySQL in Eclipse.

Steps to remember to create Java Hibernate project in Eclipse:

1. In Eclipse Project Explorer Right click -> New -> Other -> Java Project -> Enter Project Name[say BlogAuthor] -> Next and Finish.

2. Right click on the Project [BlogAuthor folder] New -> Folder -> lib

3. Paste all the above downloaded jars into the lib folder.

4. Right click on the jars inside the lib folder, Build Path -> Add to Build Path,

Project structure:

Before going further let me explain file name and the purpose of it to understand it better.

Mapping can be done using annotation or XML. Here we have done using XML.

Do you think creating XML mapping difficult ? No. It’s really very simple in eclipse using hibernate tools. Just follow the steps given in this link,

Creating hibernate XML files automatically using Hibernate Tools in Eclipse

Author.java is the mapping class which is mapped with the “AUTHOR” table.

Author.java [AUTHOR table mapping class]

package com.ngdeveloper;

public class Author {

private int authorID;

private String authorName;

// Composite class - Required entry added in the Author.hbm.xml
private SiteInfo siteInfo = new SiteInfo();

public int getAuthorID() {
return authorID;
}

public void setAuthorID(int authorID) {
this.authorID = authorID;
}

public String getAuthorName() {
return authorName;
}

public void setAuthorName(String authorName) {
this.authorName = authorName;
}

public SiteInfo getSiteInfo() {
return siteInfo;
}

public void setSiteInfo(SiteInfo siteInfo) {
this.siteInfo = siteInfo;
}

}

HibernateConfig.java is the session factory creation file, sessionfactory is the important one in hibernate along with it’s other properties like session, configuration, query, criteria and transaction.

We have shared HibernateConfig.java source code below. If you like to learn what is sessionfactory then I would recommend you to visit this below link,

How to create a session factory in hibernate ?

HibernateConfig.java: [SessionFactory creation]

package com.ngdeveloper;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateConfig {
private static SessionFactory sessionFactory;

static {
try {
// do not forget to add hibernate-jpa-2.1 [which is required jar for
// hibernate 4.3.6+]
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder standardSrvcRgstryBuilder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(standardSrvcRgstryBuilder.build());

} catch (HibernateException e) {
System.out.println("Problem while creating a sessionfactory!");
}
}

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

SiteInfo.Java is also mapping composite class of the Author.java class. Means Author.java is mapped with Author table. But the table columns are splitted for easy maintenance here as Author.java and SiteInfo.java files.

SiteInfo.java [composite class of AUTHOR table]

package com.ngdeveloper;

public class SiteInfo {

private String siteName;

private String sitePurpose;

public String getSiteName() {
return siteName;
}

public void setSiteName(String siteName) {
this.siteName = siteName;
}

public String getSitePurpose() {
return sitePurpose;
}

public void setSitePurpose(String sitePurpose) {
this.sitePurpose = sitePurpose;
}

}

Note: You can find the SiteInfo.java entry in the Author.java and Author.hbm.xml files.

hibernate.cfg.xml is the hibernate configuration xml file which will have all the datasource informations [like username,password, url, driver class, database name, dialect], mapping file configuration details.

hibernate.cfg.xml: [Hibernate configuration 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>
		<!-- MySQL JDBC Driver class -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- Enter database password -->
		<property name="hibernate.connection.password">ENTER_YOUR_DB_PASSWORD_HERE</property>
		<!-- Entry for the mysql -->
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
		<!-- username of the database -->
		<property name="hibernate.connection.username">ENTER_YOUR_DB_USERNAME_HERE</property>
		<!-- name of the schema or database -->
		<property name="hibernate.default_schema">ENTER_YOUR_DB_NAME_HERE</property>
		<!-- MySQL dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- If you make this show_sql value as true then it will print the queries -->
		<property name="hibernate.show_sql">true</property>
		<!-- When you add the below entry tables will be created automatically,
but remember it will drop and create each time you run -->
		<property name="hibernate.hbm2ddl.auto">create</property>
		<!-- Adding the hibernate mapping file entry -->
		<mapping resource="in/javadomain/Author.hbm.xml" />
	</session-factory>
</hibernate-configuration>

Author.hbm.xml: [Mapping Author.java[POJO class] with AUTHOR table[entity]]

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 10, 2015 7:17:40 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
	<class name="in.javadomain.Author" table="AUTHOR">
		<id name="authorID" type="int">
			<column name="AUTHORID" />
			<generator class="assigned" />
		</id>
		<property name="authorName" type="java.lang.String">
			<column name="AUTHORNAME" />
		</property>

		<component name="SiteInfo">
			<property name="siteName" type="java.lang.String">
				<column name="SITENAME" />
			</property>
			<property name="sitePurpose" type="java.lang.String">
				<column name="SITEPURPOSE" />
			</property>
		</component>
	</class>
</hibernate-mapping>

MainHibernate.java [for save, fetch, update etc.,]

Hibernate Save with MySQL in Java:

package com.ngdeveloper;

import org.hibernate.Session;

public class MainHibernate {
public static void main(String[] args) {
// creating the session from the sessionfactory
Session session = HibernateConfig.getSessionFactory().openSession();

/* Save starts -- Naveen - Javadomain.in */
// save or insert
session.beginTransaction();
Author author = new Author();
author.setAuthorID(3);
author.setAuthorName("Naveen kumar Gunasekaran");
author.getSiteInfo().setSiteName("Javadomain.in");
author.getSiteInfo().setSitePurpose("programming blog");
session.save(author);
session.getTransaction().commit();
/* Save ends -- Naveen - Javadomain.in */

HibernateConfig.getSessionFactory().close();
}
}

After save,

Remember, we did not create any table, because of the below entry in hibernate.cfg.xml table has been created and values are inserted. Each time you run it will drop the table and create the new one. So you can remove this entry if you do not want to drop and create after the first time run.

<property name="hibernate.hbm2ddl.auto">create</property>

Hibernate Fetch from MySQL in Java:

package com.ngdeveloper;

import org.hibernate.Session;

public class MainHibernate {
public static void main(String[] args) {
// creating the session from the sessionfactory
Session session = HibernateConfig.getSessionFactory().openSession();

// fetching starts -- Naveen - Javadomain.in // fetching or select
session.beginTransaction();
Author authorFetch = (Author) session.get(Author.class, 3);
System.out.println(authorFetch.getAuthorName());
System.out.println(authorFetch.getSiteInfo().getSiteName());
session.getTransaction().commit();
// fetching ends -- Naveen - Javadomain.in

// closing the session factory session session.close();
HibernateConfig.getSessionFactory().close();
}
}

Output:

Naveen kumar Gunasekaran
Javadomain.in

Hibernate Update with MySQL in Java:

package com.ngdeveloper;

import org.hibernate.Session;

public class MainHibernate {
public static void main(String[] args) {
// creating the session from the sessionfactory
Session session = HibernateConfig.getSessionFactory().openSession();

// fetching starts -- Naveen - Javadomain.in // fetching or select
session.beginTransaction();
Author authorFetch = (Author) session.get(Author.class, 3);
System.out.println("Before :"+authorFetch.getAuthorName());
System.out.println("Before :"+authorFetch.getSiteInfo().getSiteName());

// fetching ends -- Naveen - Javadomain.in

// update starts -- Naveen - Javadomain.in // update
authorFetch.setAuthorName("Naveen G");
authorFetch.getSiteInfo().setSiteName("www.mirthbees.com");
session.getTransaction().commit();
//update ends -- Naveen - Javadomain.in

System.out.println("After :"+authorFetch.getAuthorName());
System.out.println("After :"+authorFetch.getSiteInfo().getSiteName());
// closing the session factory session session.close();
HibernateConfig.getSessionFactory().close();
}
}

Output:

Before :Naveen kumar Gunasekaran
Before :Javadomain.in
After :Naveen G
After :www.mirthbees.com

Exit mobile version