top of page

Simple Maven Postgres Application in Hibernate using Annotation

In my previous article I talked about how to create simple application in hibernate using mapping XML. I also shared that there are two ways to map table to Object Oriented World.

So, In this article I am going to write about how to create application in hibernate by mapping table using annotation to Object Oriented World. Hibernate uses Java reflection and uses annotation for mapping. After we add annotation setting in pom.xml file we only need to add dependency to use annotation and then there will only be change in the way we map table to Object Oriented World. I will use basic annotation by creating only product class so that you do not face difficulty in understanding the code.

We will do some changes in pom.xml, Product and HibernatePersistance files to make annotation work. Rest of the steps will be same as in my previous article here.

Step 1 . Table Creation Create a database and create a table called “product”. Define a few column of the table which we will use to map to Java Class. Refer to my previous article here for code.

Step 2. Add Dependencies to Maven Project

As this is a Maven Project, so we need to add some dependencies to pom.xml file to make this application work.

If you have hibernate-common-annotation dependency already then you do not have to add this piece of code in pom.xml file.

      <id>JBoss repository</id>

Now add hibernate-common-annotation dependecy in file and rest will be same as previous article. Our whole pom.xml class will look like this.

<project xmlns="" xmlns:xsi=""
      <id>JBoss repository</id>


Step 3. Create Product Class Now this is the class that needs to be changed so that we can use annotation.

Create a file and put it in “src/main/java/com/hibernate/tutorial/” or create package in “src/main/java/” and name it “com.hibernate.tutorial”. This class will be used to store data to database later in the tutorial.

 * Model class for Product
@Table(name = "product")
public class Product implements Serializable {

     * Product Class using Annotation
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String code;
    private String name;
    private BigDecimal price;

    @GenericGenerator(name="generator", strategy="increment")
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    public void setId(Integer id) { = id;

    @Column(name = "code", unique = true, nullable = false, length = 10)
    public String getCode() {
        return code;
    public void setCode(String code) {
        this.code = code;

    @Column(name = "name", unique = true, nullable = false, length = 10)
    public String getName() {
        return name;
    public void setName(String name) { = name;

    @Column(name = "price", unique = true, nullable = false, length = 10)
    public BigDecimal getPrice() {
        return price;
    public void setPrice(BigDecimal price) {
        this.price = price;

    public String toString() {
        return "Product [id=" + id + ", code=" + code + ", name="
                + name + ", price=" + price + "]";

In my previous article I created a mapping file that maps Product class to product table in database but here we do not need to create any mapping file because we already have used annotation to map class to table.

Step 4. Postgres Configuration This file will also be changed and the change is only in mapping. We use resource when we map using xml and class for annotation.

Create a Hibernate’s configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. This is just a configuration to use some particular database. In my case I am using postgres and in the following file shows its configuration.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/sample_database</property>
        <property name="show_sql">true

Step 5. Create HibernatePersistence

This file will also be changed. We use annotation session factory instead of simple session factory.

Create a class. This will take care of Hibernate start up and retrieve the session. We use this session to store data to database using Product class using save() and commit() method. Create a persistence folder and put this file in it, “src/main/java/com/hibetnate/persistence/” or Package in “src/main/java/” and name it “com.hibernate.persistence”

public class HibernatePersistence {

private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xm
            return new AnnotationConfiguration().configure().buildSessionFactory();
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);

        public static SessionFactory getSessionFactory() {
            return sessionFactory;

        public static void shutdown() {
            // Close caches and connection pools

Step 6. Create Main Class to store values

Now we will use this class to store some data through product class to database using hibernate session. You can see this class in my previous article here.

Hope this article will help you in learning the basics of Hibernate. In my next article I am going to write about ‘How to make one-to-one relationship using Mapping XML ’. I will look forward to your suggestions and questions in the comment section.

29 views0 comments

Recent Posts

See All


Recently I got the chance to work with annotation validators @Pattern on transient field. Basically it was a password field which I had to validate first and then encrypt it and set it in another pers

Get and Load Methods in Hibernate

Both Get and Load methods in hibernate fetch row from databases. The functionality is similar but there is a difference between the way they work. hibernateSession.get() This method will return the re

Many To Many Relationship Using Annotations

This article is about how to write many to many relationships using annotations in hibernate. Many to many means that we can have many rows in one table against many rows in another table. Here is an


bottom of page