Background
This article demonstrates how to use Hibernate 4.3.x with MySQL 5.6.16 in Java using JDBC.
Software Environment
- Windows 7 Professional SP1
- Eclipse – Kepler Release
- Java 1.7 (1.7.0_67 – Windows x86)
- MySQL 5.6.16 – Community Server (GPL)
- MySQL Java Connector 5.1.6
- Hibernate 4.3.7
Database Set Up
The schema contains 3 tables – T_PERSON, T_EDUCATION, and T_CERTIFICATION. They represent a simple profile for a person in a typical job site like LinkedIn or Monster.com. Run these statements in MySQL Server against a database named hibernatesampledb in the order they are listed here.
Person Table
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `t_person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lastname` varchar(30) NOT NULL, `firstname` varchar(30) NOT NULL, `middlename` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3; |
Education Table
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `t_education` ( `eid` int(11) NOT NULL AUTO_INCREMENT, `school_name` varchar(30) NOT NULL, `pid` int(11) NOT NULL, PRIMARY KEY (`eid`), KEY `p_id` (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7; |
Certification Table
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `t_certification` ( `cid` int(11) NOT NULL AUTO_INCREMENT, `cert_name` varchar(30) NOT NULL, `pid` int(11) NOT NULL, PRIMARY KEY (`cid`), KEY `p_id` (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7; |
Keys and Indexes
1 2 3 4 5 6 7 8 9 10 11 | -- -- Constraints for table `t_certification` -- ALTER TABLE `t_certification` ADD CONSTRAINT `t_certification_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `t_person` (`id`); -- -- Constraints for table `t_education` -- ALTER TABLE `t_education` ADD CONSTRAINT `t_education_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `t_person` (`id`); |
Create Maven Project
Creating a Maven project is simple. For instructions, please follow the instructions on How to create the Maven project in Eclipse.
Java Classes
PersonBean Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | package com.turreta.hibernateapp.bean; import java.util.List; public class PersonBean { private int id; private String firstName; private String lastName; private String middleName; private List<EducationBean> educationList; private List<CertificationBean> certificationList; public List<Educationbean> getEducationList() { return educationList; } public void setEducationList(List<EducationBean> educationList) { this.educationList = educationList; } public List<CertificationBean> getCertificationList() { return certificationList; } public void setCertificationList(List<CertificationBean> certificationList) { this.certificationList = certificationList; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } } |
EducationBean Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package com.turreta.hibernateapp.bean; public class EducationBean { private int eid; private String schoolName; private PersonBean person; public EducationBean() { } public EducationBean(String schoolName, PersonBean person) { this.schoolName = schoolName; this.person = person; } public int getEid() { return eid; } public void setEid(int eid) { this.eid = eid; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public PersonBean getPerson() { return person; } public void setPerson(PersonBean person) { this.person = person; } } |
CertificationBean Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.turreta.hibernateapp.bean; public class CertificationBean { private int cid; private String certName; private PersonBean person; public CertificationBean() { } public CertificationBean(String certName, PersonBean person) { this.certName = certName; this.person = person; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getCertName() { return certName; } public void setCertName(String certName) { this.certName = certName; } public PersonBean getPerson() { return person; } public void setPerson(PersonBean person) { this.person = person; } } |
Main Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | package com.turreta.hibernateapp; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.turreta.hibernateapp.bean.CertificationBean; import com.turreta.hibernateapp.bean.EducationBean; import com.turreta.hibernateapp.bean.PersonBean; public class MavenSampleMain { public static void main(String[] args) { PersonBean person = new PersonBean(); person.setLastName("Doe"); person.setFirstName("John"); person.setMiddleName("Anonymous"); EducationBean education01 = new EducationBean("School A", person); EducationBean education02 = new EducationBean("School B", person); EducationBean education03 = new EducationBean("School C", person); CertificationBean certification01 = new CertificationBean( "Certification A", person); CertificationBean certification02 = new CertificationBean( "Certification B", person); CertificationBean certification03 = new CertificationBean( "Certification C", person); SessionFactory sessionFactory = null; Session session = null; Transaction tx = null; try { sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.getCurrentSession(); tx = session.beginTransaction(); session.save(person); session.save(education01); session.save(education02); session.save(education03); session.save(certification01); session.save(certification02); session.save(certification03); // Commit transaction tx.commit(); System.out.println("Person ID=" + person.getId()); } catch (Exception e) { System.out.println("Exception occured. " + e.getMessage()); e.printStackTrace(); } finally { if (!sessionFactory.isClosed()) { sessionFactory.close(); } } } } class HibernateUtil { private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); System.out.println("Hibernate serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; } } |
Hibernate Mapping Files
Person.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <hibernate-mapping package="com.turreta.hibernateapp.bean"> <class name="PersonBean" table="t_person"> <id column="id" name="id"> <generator class="increment"> </generator></id> <property column="lastname" name="lastName"> <property column="firstname" name="firstName"> <property column="middlename" name="middleName"> <set fetch="select" name="educationList" table="t_education"> <key> <column name="pid" not-null="true"></column> </key> <one-to-many class="EducationBean"> </one-to-many></set> <set fetch="select" name="certificationList" table="t_certification"> <key> <column name="pid" not-null="true"></column> </key> <one-to-many class="CertificationBean"> </one-to-many></set> </property></property></property></class> </hibernate-mapping> |
Education.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 | <hibernate-mapping package="com.turreta.hibernateapp.bean"> <class name="EducationBean" table="t_education"> <id column="eid" name="eid"> <generator class="increment"> </generator></id> <property column="school_name" name="schoolName"> <many-to-one class="PersonBean" name="person"> <column name="pid" not-null="true"></column> </many-to-one> </property></class> </hibernate-mapping> |
Certification.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 | <hibernate-mapping package="com.turreta.hibernateapp.bean"> <class name="CertificationBean" table="t_certification"> <id column="cid" name="cid"> <generator class="increment"> </generator></id> <property column="cert_name" name="certName"> <many-to-one class="PersonBean" name="person"> <column name="pid" not-null="true"></column> </many-to-one> </property></class> </hibernate-mapping> |
Configure pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.turreta.hibernate</groupid> <artifactid>hibernateapp</artifactid> <version>0.0.1-SNAPSHOT</version> <name>Hibernate app</name> <dependencies> <dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-core</artifactid> <version>4.3.7.Final</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.6</version> </dependency> </dependencies> </project> |
hibernate.cfg.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernatesampledb</property> <property name="connection.username">root</property> <property name="connection.password">password</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">10</property> <property name="hibernate.current_session_context_class">thread</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Mapping files --> <mapping resource="com/turreta/hibernateapp/bean/Person.hbm.xml"> <mapping resource="com/turreta/hibernateapp/bean/Education.hbm.xml"> <mapping resource="com/turreta/hibernateapp/bean/Certification.hbm.xml"> </mapping></mapping></mapping></session-factory> </hibernate-configuration> |
Download the Project
https://www.dropbox.com/s/31ng35gfc9uzoes/turreta-hibernateapp.zip?dl=0