Hibernate in Eclipse with PostgreSQL Example
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 with JDBC. Try Java 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, click File -> New -> Other -> Maven Project (type maven in the text box) -> Next. Tick Create a simple project -> Next. Enter the com.javacodegeeks.example for the Group Id and hibernate-eclipse-postgresql for the Artifact Id and then click Finish.
Add the following dependencies to your project:
- hibernate-entitymanager v3.4.0.GA
- postgresql v42.2.2.jre7
- slf4j-log4j12 v1.4.2
- junit v4.12
Your pom.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 package com.javacodegeeks.example
in src/main/java. Create Car.java
under this package.
Car.java
package com.javacodegeeks.example; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Car implements Serializable { private static final long serialVersionUID = 1L; @Id private 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 named car
. The primary key is specified by the @Id
annotation. In this case, model is the primary key and the table will have model
and price
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 package com.javacodegeeks.example
in src/test/java. Create Runner.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 { @Test public 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 new Car
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 the Car
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 file hibernate.cfg.xml
in src/main/resources.
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 class="com.javacodegeeks.example.Car"/> </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 for hibernate.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 the SessionFactory
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 click Runner.java
Run 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.
You can download the source code of this example here: hibernate-eclipse-postgresql.zip.
thanks a lot. this is actually the first hibernate tutorial that worked for me.
btw i had an error in class runner. To solve it I had to type List cars instead of List cars on line 69.
Keep doing the good work !
You’re welcome Alexandru. You are correct it should have been
My mistake in html escaping the code but the downloadable source code is correct.
How is this translated query
select car0_.model as model0_, car0_.price as price0_ from Car car0_
not throwing an error for the table name car0 not found.
?
Hi Anuj,
That is Hibernate logging output. That’s internal to the Hibernate framework.
Cheers,
Joel
Lits cars = q.list(); and further on down for(Car c : cars) doesn’t work anymore due to list being a raw type. Any workaround for this?
Edit: My apologies, I didn’t see this question has been asked and answered. Thank you for your help.