
Play Store Application link β Hibernate – in 10 steps – Apps on Google Play
Github project link (XML version) – https://github.com/kuldeep101990/HibernateSimpleCrud
Github project link (Annotation version)- https://github.com/kuldeep101990/HibernateSimpleCrudAnnotated
Here we are going to perform following operations-
- Saving objects
- Retrieving objects
- Updating objects
- Deleting objects
First, we will configure everything which will be needed-
1- Class (which need to be saved/updated/deleted and retrieved.
2- Hibernate Configuration file
3- Hibernate Mapping File
4- Create the Hibernate SessionFactory object
5- Open a Hibernate session
1- Class, we going to use for all above operations is below-
import java.util.Date;
public class Person {
private long id;
private String name;
private Date dob;
public Person() {
}
public Person(String name, Date dob) {
this.name = name;
this.dob = dob;
}
// getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
2- Hibernate configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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.url">jdbc:mysql://localhost:3306/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3- Hibernate Mapping File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Person" table="person">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"/>
<property name="dob" column="dob"/>
</class>
</hibernate-mapping>
4- Create the Hibernate SessionFactory object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
5- Open a Hibernate session
Session session = sessionFactory.openSession();
– Saving objects-
To save a persistent object using Hibernate in a MySQL database with XML configuration and XML mapping files, you need to follow these steps:
Step1 – Create a Person object –
Create a Person object and set its properties using the setter methods.
Person person = new Person();
person.setName("Kuldeep kaushik");
person.setDob(new Date());
ο»Ώ
Step 2: Save the Person object
Save the Person object using the save() method of the Hibernate session.
Transaction transaction = session.beginTransaction();
session.save(person);
transaction.commit();
ο»Ώ
Step 3: Close the Hibernate session
Close the Hibernate session to release the database connection and free up resources.
session.close();
That’s it! Your Person object has been saved as a persistent object in the MySQL database using Hibernate with XML configuration and XML mapping files.
So complete code will look like this-
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Step 1: Set up the Hibernate configuration file
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Step 2: Define the Hibernate mapping file
// Person.hbm.xml is already defined
// Step 3: Create the Hibernate SessionFactory object
SessionFactory sessionFactory = cfg.buildSessionFactory();
// Step 4: Open a Hibernate session
Session session = sessionFactory.openSession();
// Step 5: Create a Person object
Person person = new Person();
person.setName("Kuldeep kaushik");
person.setDob(new Date());
// Step 6: Save the Person object
Transaction transaction = session.beginTransaction();
session.save(person);
transaction.commit();
// Step 7: Close the Hibernate session
session.close();
}
}
Similarly, for Retrieving/Updating/Deleting-
Complete code will be –
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
public class Main {
public static void main(String[] args) {
// Step 1: Set up the Hibernate configuration file
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Step 2: Define the Hibernate mapping file
// Person.hbm.xml is already defined
// Step 3: Create the Hibernate SessionFactory object
SessionFactory sessionFactory = cfg.buildSessionFactory();
// Step 4: Open a Hibernate session
Session session = sessionFactory.openSession();
// Step 5: Create and save a new Person object
Person person = new Person();
person.setName("Kuldeep kaushik");
person.setDob(new Date());
Transaction transaction = session.beginTransaction();
session.save(person);
transaction.commit();
// Step 6: Update the Person object
transaction = session.beginTransaction();
person.setName("Kuldeep sharma");
session.update(person);
transaction.commit();
// Step 7: Retrieve the Person object
Query<Person> query = session.createQuery("from Person where id = :id");
query.setParameter("id", person.getId());
List<Person> results = query.list();
if (!results.isEmpty()) {
Person retrievedPerson = results.get(0);
System.out.println("Retrieved person: " + retrievedPerson.getName() + " (DOB: " + retrievedPerson.getDob() + ")");
} else {
System.out.println("No person found with id " + person.getId());
}
// Step 8: Delete the Person object
transaction = session.beginTransaction();
session.delete(person);
transaction.commit();
// Step 9: Close the Hibernate session
session.close();
}
}
Note – Here’s a breakdown of the changes made to the Main
class:
- After saving the
Person
object, a new transaction is started to update thePerson
object. The name is changed to “Kuldeep sharma” and the updated object is saved to the database. - A new query is created to retrieve the
Person
object using theid
property. The query is parameterized to avoid SQL injection attacks. - The results of the query are retrieved and checked to see if any objects were returned. If a
Person
object was returned, its name and DOB are printed to the console. Otherwise, a message indicating that noPerson
object was found is printed. - Another transaction is started to delete the
Person
object from the database. - The Hibernate session is closed to free up resources.
[…] Step 5- Working with Persistent Objects […]