In this Hibernate example, we will learn how to create a simple Hibernate application using Java-based configuration without XML configuration in Eclipse IDE. We use Maven as a build tool and MySQL database to store the data.
Hibernate is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database. Object-relational mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
Development Steps
- Create a Simple Maven Project
- Project Directory Structure
- Add jar Dependencies to pom.xml
- Creating the JPA Entity Class(Persistent class)
- Create a Hibernate Java-based configuration file - HibernateUtil.java
- Create StudentDao class
- Create the Main class and Run an Application
1. Create a Simple Maven Project
Use How to Create a Simple Maven Project in Eclipse article to create a simple Maven project in Eclipse IDE.
2. Project Directory Structure
3. Add jar Dependencies to pom.xml
<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>net.javaguides</groupId>
<artifactId>hibernate-java-config-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
</dependencies>
</project>
4. Creating the JPA Entity Class(Persistent class)
Let's create a Student persistent class that is mapped to a student database table:
package net.javaguides.hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
5. Create a Hibernate Java-based configuration file - HibernateUtil.java
Note that we are creating Hibernate Application using Java configuration without using hibernate.cfg.xml to connect the MySQL database.
package net.javaguides.hibernate.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import net.javaguides.hibernate.model.Student;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/java_dmeo?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
6. Create StudentDao Class
Let's create a separate StudentDao class to separate out hibernate related stuff.
package net.javaguides.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.model.Student;
import net.javaguides.hibernate.util.HibernateUtil;
public class StudentDao {
public void saveStudent(Student student) {
Transaction transaction = null;
// auto close session object
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start the transaction
transaction = session.beginTransaction();
// save student object
session.save(student);
// commit transction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
}
7. Create the Main class and Run an Application
Let's test Hibernate application to connect MySQL database.
package net.javaguides.hibernate;
import net.javaguides.hibernate.dao.StudentDao;
import net.javaguides.hibernate.model.Student;
public class App {
public static void main(String[] args) {
StudentDao studentDao = new StudentDao();
Student student = new Student("Ramesh", "Fadatare", "ramesh@gmail.com");
studentDao.saveStudent(student);
System.out.println(student.getId());
}
}
Output
References
Eclipse
Hibernate Framework
Java
Maven
Comments
Post a Comment