CRUD using Hibernate, MySQL & Maven
This tutorial explains how to perform a simple CRUD using Hibernate, Maven and MySQL as Database.
1. Project Setup
Lets create a simple Maven project with the below pom.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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<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.heapcode.hibernate</groupId> <artifactId>hibernate-basic</artifactId> <version>1.0</version> <packaging>pom</packaging> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.5</version> </dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project> |
In the above pom.xml we added dependencies for Hibernate 3.6.10, MySQL Connector 5.1.25, javassist and sl4j for logging.
2. Database Table Creation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
CREATE TABLE `EMPLOYEE` ( `EMPLOYEE_ID_PK` int(10) unsigned NOT NULL AUTO_INCREMENT, `FIRST_NAME` varchar(45) NOT NULL, `LAST_NAME` varchar(45) DEFAULT NULL, `EMAIL` varchar(45) NOT NULL, `PHONE_NO` int(11) NOT NULL, `CREATED_BY` int(10) unsigned NOT NULL, `CREATED_DATE` datetime NOT NULL, `MODIFIED_BY` int(10) unsigned NOT NULL, `MODIFIED_DATE` datetime NOT NULL, PRIMARY KEY (`EMPLOYEE_ID_PK`), UNIQUE KEY `EMAIL_UNIQUE` (`EMAIL`), UNIQUE KEY `EMPLOYEE_ID_PK_UNIQUE` (`EMPLOYEE_ID_PK`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1$$ |
The above script creates a table EMPLOYEE which looks as below
3. Java POJO Class
Lets us create a Java POJO Bean Class Employee.java which is basically a Object Map of the above EMPLOYEE Table.
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 95 96 97 98 99 100 101 102 103 104 105 106 107 |
package com.heapcode.hibernate.entity; import java.io.Serializable; import java.util.Date; /** * @author Manjunath Sampath * */ public class Employee implements Serializable { private static final long serialVersionUID = -6213555350782474664L; public Employee(){ } private int employeeIdPk; private String firstName; private String lastName; private String email; private Integer phoneNo; private int createdBy; private Date createdDate; private int modifiedBy; private Date modifiedDate; public int getEmployeeIdPk() { return employeeIdPk; } public void setEmployeeIdPk(int employeeIdPk) { this.employeeIdPk = employeeIdPk; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getPhoneNo() { return phoneNo; } public void setPhoneNo(Integer phoneNo) { this.phoneNo = phoneNo; } public int getCreatedBy() { return createdBy; } public void setCreatedBy(int createdBy) { this.createdBy = createdBy; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public int getModifiedBy() { return modifiedBy; } public void setModifiedBy(int modifiedBy) { this.modifiedBy = modifiedBy; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } } |
4. Create a Mapping File
Lets us create a mapping file for the above EMPLOYEE Table and Employee.java Bean. This is basically a mapping for Hibernate to understand which column in database table corresponds to which field in Java Bean
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 |
<?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"> <hibernate-mapping package="com.heapcode.hibernate.entity"> <class name="Employee" table="EMPLOYEE" catalog="heapcode"> <id name="employeeIdPk" type="java.lang.Integer"> <column name="EMPLOYEE_ID_PK" /> <generator class="identity" /> </id> <property name="firstName" type="java.lang.String"> <column name="FIRST_NAME" length="10" not-null="true" /> </property> <property name="lastName" type="java.lang.String"> <column name="LAST_NAME" length="45" /> </property> <property name="email" type="java.lang.String"> <column name="EMAIL" length="45" not-null="true" /> </property> <property name="phoneNo" type="java.lang.Integer"> <column name="PHONE_NO" not-null="true" /> </property> <property name="createdBy" type="java.lang.Integer"> <column name="CREATED_BY" not-null="true" /> </property> <property name="createdDate" type="java.util.Date"> <column name="CREATED_DATE" not-null="true" length="4"/> </property> <property name="modifiedBy" type="java.lang.Integer"> <column name="MODIFIED_BY" not-null="true" /> </property> <property name="modifiedDate" type="java.util.Date"> <column name="MODIFIED_DATE" not-null="true" length="4"/> </property> </class> </hibernate-mapping> |
5. Configuring Hibernate
Now let us create the Hibernate Configuration file hibernate.cfg.xml. This is the master Hibernate Configuration File wherein we specify the Database URL, Credentials and specify the various mapping files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?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.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">heapcode</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/heapcode</property> <property name="hibernate.connection.username">heapcode</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="show_sql">true</property> <mapping resource="Employee.hbm.xml"></mapping> </session-factory> </hibernate-configuration> |
6. Project Structure
The project after the above configuration would look like
7. CRUD Operation
1. CREATE
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 |
package com.heapcode.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.heapcode.hibernate.entity.Employee; /** * @author msampath * */ public class HibernateMain { public static void main(String[] args) { HibernateMain hibernateMain = new HibernateMain(); hibernateMain.create(); } private void create() { SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session = sf.openSession(); Employee employee = new Employee(); employee.setFirstName("John"); employee.setLastName("Trodd"); employee.setPhoneNo(12345); employee.setCreatedBy(0); employee.setModifiedBy(0); employee.setCreatedDate(new Date()); employee.setModifiedDate(new Date()); Transaction tx = null; try{ tx = session.getTransaction(); tx.begin(); session.save(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } session.close(); sf.close(); } } |
2. READ
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 |
package com.heapcode.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.heapcode.hibernate.entity.Employee; /** * @author Manjunath Sampath * */ public class HibernateMain { public static void main(String[] args) { HibernateMain hibernateMain = new HibernateMain(); hibernateMain.read(); } private void read(){ SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session = sf.openSession(); Employee employee = (Employee) session.load(Employee.class, 4); System.out.println(employee.getFirstName()); System.out.println(employee.getLastName()); System.out.println(employee.getEmail()); session.close(); sf.close(); } } |
3. UPDATE
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 |
package com.heapcode.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.heapcode.hibernate.entity.Employee; /** * @author Manjunath Sampath * */ public class HibernateMain { public static void main(String[] args) { HibernateMain hibernateMain = new HibernateMain(); hibernateMain.update(); } private void update(){ SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session = sf.openSession(); Employee employee = (Employee) session.load(Employee.class, 4); employee.setPhoneNo(23456); Transaction tx = null; try{ tx = session.getTransaction(); tx.begin(); session.saveOrUpdate(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } session.close(); sf.close(); } } |
4. DELETE
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 |
package com.heapcode.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.heapcode.hibernate.entity.Employee; /** * @author Manjunath Sampath * */ public class HibernateMain { public static void main(String[] args) { HibernateMain hibernateMain = new HibernateMain(); hibernateMain.delete(); } private void delete(){ SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session = sf.openSession(); Employee employee = (Employee) session.load(Employee.class, 4); Transaction tx = null; try{ tx = session.getTransaction(); tx.begin(); session.delete(employee); tx.commit(); }catch(RuntimeException re){ tx.rollback(); re.printStackTrace(); } session.close(); sf.close(); } } |
Download Hibernate_MySQL_Maven_Example_Project
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.
Thanks a lot…
Welcome Vengat!