hibernate

Hibernate in Eclipse with PostgreSQL Example

Photo of Joel Patrick LlosaJoel Patrick LlosaJuly 13th, 2018Last Updated: February 20th, 2019
5 1,813 4 minutes read

This article will show you a simple example of how to use Hibernate in Eclipse with PostgreSQL. PostgreSQL is an object-relational database management system. It’s one of the most popular databases used in the world. Hibernate is a framework for mapping object-oriented domain model to a relational database. Hibernate handles persistent database accesses with high-level object handling functions.

1. Assumptions

This article assumes that the reader has used PostgreSQL withJDBC. TryJava JDBC PostgreSQL Connection Example if you haven’t done so.
The example here has been created using Eclipse Oxygen on a Windows 10 machine. All explanations will refer to this environment setup. If you have a different environment, the steps in creating this project should be similar.

2. Create the Project

Fire up Eclipse and create a Maven project, clickFile -> New -> Other -> Maven Project (type maven in the text box) -> Next. TickCreate a simple project -> Next. Enter thecom.javacodegeeks.example for theGroup Id andhibernate-eclipse-postgresql for theArtifact Id and then clickFinish.
Add the following dependencies to your project:

  1. hibernate-entitymanager v3.4.0.GA
  2. postgresql v42.2.2.jre7
  3. slf4j-log4j12 v1.4.2
  4. junit v4.12

Yourpom.xml should look like the one below:

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>com.javacodegeeks.example</groupId>  <artifactId>hibernate-eclipse-postgresql</artifactId>  <version>0.0.1-SNAPSHOT</version>  <dependencies>    <dependency>      <groupId>hibernate</groupId>      <artifactId>hibernate-entitymanager</artifactId>      <version>3.4.0.GA</version>    </dependency>    <dependency>      <groupId>org.postgresql</groupId>      <artifactId>postgresql</artifactId>      <version>42.2.2.jre7</version>    </dependency>    <dependency>      <groupId>org.slf4j</groupId>      <artifactId>slf4j-log4j12</artifactId>      <version>1.4.2</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>    </dependency>  </dependencies></project>

3. Create the Model

Create the packagecom.javacodegeeks.example insrc/main/java. CreateCar.java under this package.

Car.java

package com.javacodegeeks.example;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.Id;@Entitypublic class Car implements Serializable {private static final long serialVersionUID = 1L;@Idprivate String model;private String price;public String getModel() {return model;}public void setModel(String model) {this.model = model;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}}

This class will represent a row in the database table. Since no name is specified by@Entity, the table will be namedcar. The primary key is specified by the@Id annotation. In this case, model is the primary key and the table will havemodel andprice as columns. Both the columns are of type varchar.

4. Create, Read, Update, Delete

We’ll utilize a test to drive our create, read, update, and delete operations on the database. Create the packagecom.javacodegeeks.example insrc/test/java. CreateRunner.java under this package.

Create the source below:

Runner.java

package com.javacodegeeks.example;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.junit.Test;public class Runner {@Testpublic void crud() {SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();Session session = sessionFactory.openSession();create(session);read(session);update(session);read(session);delete(session);read(session);session.close();}private void delete(Session session) {System.out.println("Deleting mondeo record...");Car mondeo = (Car) session.get(Car.class, "mondeo");session.beginTransaction();session.delete(mondeo);session.getTransaction().commit();}private void update(Session session) {System.out.println("Updating mustang price...");Car mustang = (Car) session.get(Car.class, "mustang");mustang.setModel("mustang");mustang.setPrice("£35,250.00");session.beginTransaction();session.saveOrUpdate(mustang);session.getTransaction().commit();}private void create(Session session) {System.out.println("Creating car records...");Car mustang = new Car();mustang.setModel("mustang");mustang.setPrice("£40,000.00");Car mondeo = new Car();mondeo.setModel("mondeo");mondeo.setPrice("£20,000.00");session.beginTransaction();session.save(mustang);session.save(mondeo);session.getTransaction().commit();}private void read(Session session) {Query q = session.createQuery("select _car from Car _car");List cars = q.list();System.out.println("Reading car records...");System.out.printf("%-30.30s  %-30.30s%n", "Model", "Price");for (Car c : cars) {System.out.printf("%-30.30s  %-30.30s%n", c.getModel(), c.getPrice());}}}

First off, you create a session and then open it. To create records, you create a newCar instance, begin a transaction, save the object and then commit the transaction. To read records, you create a query and then get a list of the objects from the query. To update, you get the record based on the primary key, update theCar object returned and save it by starting a transaction and then committing it. To delete a record, you get the record by specifying the primary key and then invoke a delete transaction.

5. Configure Hibernate

Next up is to create the Hibernate configuration file. Create the configuration filehibernate.cfg.xml insrc/main/resources.

Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright now!
In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

hibernate.cfg.xml

<?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>         <!-- Connection settings -->        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/example</property>        <property name="hibernate.connection.username">ostgres</property>        <property name="hibernate.connection.password">postgres</property>         <!-- SQL dialect -->        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>         <!-- Print executed SQL to stdout -->        <property name="show_sql">true</property>         <!-- Update database on startup -->        <property name="hibernate.hbm2ddl.auto">update</property>         <!-- Annotated entity classes -->        <mapping/>            </session-factory></hibernate-configuration>

This configuration file tells us the connection settings to the database. It tells us that Hibernate will use the PostgreSQL dialect. It will show the SQL statements being used by Hibernate. Hibernate will automatically update the schema on startup. Other options forhibernate.hbm2ddl.auto are validate (validate the schema, makes no changes to the database), create (creates the schema, destroying previous data), and create-drop (drop the schema when theSessionFactory is closed explicitly). Bear in mind that automatic schema generation is not recommended in a production environment.

6. Hibernate in Eclipse with PostgreSQL Output

Run the test, right clickRunner.javaRun As -> JUnit Test. You should see the output below when you run the program.

Console Output

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).log4j:WARN Please initialize the log4j system properly.Creating car records...Hibernate: insert into Car (price, model) values (?, ?)Hibernate: insert into Car (price, model) values (?, ?)Hibernate: select car0_.model as model0_, car0_.price as price0_ from Car car0_Reading car records...Model                           Price                         mustang                         £40,000.00                    mondeo                          £20,000.00                    Updating mustang price...Hibernate: update Car set price=? where model=?Hibernate: select car0_.model as model0_, car0_.price as price0_ from Car car0_Reading car records...Model                           Price                         mondeo                          £20,000.00                    mustang                         £35,250.00                    Deleting mondeo record...Hibernate: delete from Car where model=?Hibernate: select car0_.model as model0_, car0_.price as price0_ from Car car0_Reading car records...Model                           Price                         mustang                         £35,250.00

To run the test again, you’ll need to empty the records. Otherwise you’ll get an error that a record already exists. You can do this using pgAdmin. The SQL statements are shown by Hibernate because we set it in our configuration file.

7. Hibernate in Eclipse with PostgreSQL Summary

To summarize, you need to make an entity class to define the records of the database. Next, configure Hibernate to use PostgreSQL. After that, open a session to make operations on the database. To make changes, start a transaction, do the operation and then commit the changes. Create a query to read the records. Make sure to close the session when you are finished using it. That’s all there is to it.

8. Download the Source Code

This is an example about Hibernate in Eclipse with PostgreSQL.

Download
You can download the source code of this example here:hibernate-eclipse-postgresql.zip.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Joel Patrick LlosaJoel Patrick LlosaJuly 13th, 2018Last Updated: February 20th, 2019
5 1,813 4 minutes read
Photo of Joel Patrick Llosa

Joel Patrick Llosa

I graduated from Silliman University in Dumaguete City with a degree in Bachelor of Science in Business Computer Application. I have contributed to many Java related projects at Neural Technologies Ltd., University of Southampton (iSolutions), Predictive Technologies, LLC., Confluence Service, North Concepts, Inc., NEC Telecom Software Philippines, Inc., and NEC Technologies Philippines, Inc. You can also find me in Upwork freelancing as a Java Developer.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.