Mark Addison bio photo

Mark Addison

Software Engineer from Surrey England

Email Twitter Google+ LinkedIn Github Stackoverflow

Overview

This tutorial will show you how to use annotation with Spring Hibernate

Prerequisites

You will need to install the following technical components:

  • Java 1.7.x
  • Maven 3.0.5
  • Spring Framework 3.0.6
  • Hibernate 3.6.3

Create a new Java project in Maven

The simplest way to quickly create a new Java project in Maven is to utilise Maven Archetype (Quickstart)

$ mvn archetype:generate -DgroupId=com.addison.database -DartifactId=SpringHibernateUsingAnnotations -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Java project skeleton structure

SpringHibernateUsingAnnotations
│   pom.xml
│
└───src
    ├───main
    │   └───java
    │       └───com
    │           └───addison
    │               └───database
    │                       App.java
    │
    └───test
        └───java
            └───com
                └───addison
                    └───database
                            AppTest.java

This essentailly creates a Hello world application! Since we do not need App or AppTest classes, these should just be deleted.

Data Entities

For this example let us consider persisting a Trade entity, with attributes product name, product code, bur or sell, quantity, price, trade date; and an Account, which is modelled as another first class entity.

Annotated Trade Entity & Columns

import javax.persistence.*;

@Entity
public class Trade {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "trade_id", nullable = false, insertable = false, updatable = false)
    private Long tradeId;

    @Column(name = "buySell", nullable = false, length = 4)
    private String buySell;

    @Column(name = "quantity", nullable = false)
    private Double quantity;

    @Column(name = "symbol", nullable = true, length = 20)
    private String symbol;

    @Column(name = "price", nullable = false)
    private Double price;

    @ManyToOne(cascade = CascadeType.ALL)
    private Account account;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "trade_date", nullable = false)
    public java.util.Date tradeDate = new java.util.Date();
}

Annotated Account Entity & Columns

import javax.persistence.*;

@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "account_id", nullable = false, insertable = false, updatable = false)
    private Long accountId;

    @Column(name = "name", nullable = false, length = 40)
    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "creation_date", nullable = false)
    private java.util.Date creationDate = new Date();

    @OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
    private Set<Trade> trades = new HashSet<Trade>();
}

This is my hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- Database connection settings, Connect to HSQL -->
    <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
    <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="connection.url">jdbc:hsqldb:mem:testdb</property>
    <property name="connection.username">SA</property>
    <property name="connection.password"></property>
    <!-- property name="show_sql">true</property>
    <property name="format_sql">true</property -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <!--create the database schema on startup if required -->
    <property name="hbm2ddl.auto">create</property>
    <mapping class="com.addison.database.entity.Account"></mapping>
    <mapping class="com.addison.database.entity.Trade"></mapping>
  </session-factory>
</hibernate-configuration>

Code

The source code is available from my public Github repository SpringHibernateUsingAnnotations