How to use Hibernate Annotations to work with Database

Hibernate annotations is a solution to map Java classes and database’s tables without using XML file. So in the tutorial, JavaSampleApproach will guide you through the steps of configuring Hibernate Annotations to work with Database.

Related articles:
How to start development with Hibernate – XML Mapping File Hibernate

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Hibernate: 5.2.10.Final
– MySQL 5.7

II. Hibernate Annotations

We use annotations at standard package java.lang.annotation.* of EJB 3.
We have MySQL table:

How to use annotations to map it with Java Entity class?

– Approach 1: use annotations on fields to access properties on an object through fields.

– Approach 2: use annotations on the getXXX() methods to enable access to properties through getter and setter methods.

@javax.persistence.Entity: specifies the entity class.
– Having option attribute: name that is used for specifying a mapping table.

@javax.persistence.Column: specifies the mapped column for a persistent property or field. Below is common optional attributes of @Column:
name: is a column’s name , defaults to the property name.
unique: defines the column is a unique key, default is false.
nullable: specify the column is nullable, default value is true.
length: specify length of string-valued column.

@javax.persistence.Id: specifies the primary key of an entity.

@javax.persistence.GeneratedValue: generates the values of primary keys. It’s only supported for simple primary keys and Not supported for derived primary keys.

III. Practice

Step to do:
– Create Spring Maven project
– Create persistent class
– Setup Hibernate configuration
– Implement Hibernate Application
– Run & Check Results

1. Create Spring Maven project

Using Spring Tool Suite, create a Simple Spring Maven project.
Modified pom.xml file with Hibernate & MySql dependencies:

2. Create persistent class

Create a Customer.java:

3. Setup Hibernate configuration

Under /src/main/resources, create Hibernate Configuration file – hibernate.cfg.xml:

– We use property hibernate.hbm2ddl.auto with create value to init customer table automatically. Or we can manually create customer table by SQL script:

4. Implement Hibernate Application

– Implement 6 functions:
setUpSessionFactory(): setup Hibernate Session Factory
saveCustomers(): save Customers to Database by Hibernate
showAllCustomers(): retrieve all customers from MySQL and show all on console.
updateCustomer(int customerId, int newAge): update Customer’s age.
deleteCustomer(int customerId): delete a customer
shutdown(): close Hiberbate Session Factory Object

5. Run & Check Results

– Run the main class Application.java, Logs:

– Customer’s records:

hibernate annotation - customer records

IV. Sourcecode

SpringHibernateAnnotations


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*