How to use Hibernate Annotations to work with Database

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:

CREATE TABLE customer(
   id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(20) NOT NULL,
   lastname VARCHAR(20) NOT NULL,
   age INT NOT NULL,
   PRIMARY KEY (id)
);

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.

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private int id;
	
	@Column(name = "firstname", nullable=false)
	private String firstName;
	
	@Column(name = "lastname", nullable=false)
	private String lastName;
	
	@Column(name = "age", nullable=false)
	private int age;
	
	public Customer(){};
	
	public Customer(String firstName, String lastName, int age){
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
        // getters & setters
...

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

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	private int id;

	private String firstName;

	private String lastName;

	private int age;

	public Customer() {
	};

	public Customer(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	public int getId() {
		return this.id;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@Column(name = "firstname", nullable = false)
	public String getFirstName() {
		return this.firstName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Column(name = "lastname", nullable = false)
	public String getLastName() {
		return this.lastName;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Column(name = "age", nullable = false)
	public int getAge() {
		return this.age;
	}

	public String toString() {
		String info = String.format("Customer info: id = %d, firstname = %s, lastname = %s, age = %d", id, firstName,
				lastName, age);
		return info;
	}

}

@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:


    4.0.0
    org.springframework.samples
    SpringHibernateStarter
    0.0.1
     
    
        
        
            org.hibernate
            hibernate-core
            5.2.10.Final
        
         
        
        
            mysql
            mysql-connector-java
            6.0.6
        
         
         
    

2. Create persistent class

Create a Customer.java:

package com.javasampleapproach.hibernate.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	private int id;
	
	@Column(name = "firstname", nullable=false)
	private String firstName;
	
	@Column(name = "lastname", nullable=false)
	private String lastName;
	
	@Column(name = "age", nullable=false)
	private int age;
	
	public Customer(){};
	
	public Customer(String firstName, String lastName, int age){
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
	public void setId(int id){
		this.id = id;
	}
	
	public int getId(){
		return this.id;
	}
	
	public void setFirstName(String firstName){
		this.firstName = firstName;
	}
	
	public String getFirstName(){
		return this.firstName;
	}
	
	public void setLastName(String lastName){
		this.lastName = lastName;
	}
	
	public String getLastName(){
		return this.lastName;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return this.age;
	}
	
	public String toString(){
		String info = String.format("Customer info: id = %d, firstname = %s, lastname = %s, age = %d", 
														id, firstName, lastName, age);
		return info;
	}

}
3. Setup Hibernate configuration

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




    
    	jdbc:mysql://localhost:3306/testdb
        com.mysql.jdbc.Driver
        root
        12345
        org.hibernate.dialect.MySQL5Dialect
        create
        true
    

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

CREATE TABLE customer(
   id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(20) NOT NULL,
   lastname VARCHAR(20) NOT NULL,
   age INT NOT NULL,
   PRIMARY KEY (id)
);
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

package com.javasampleapproach.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.javasampleapproach.hibernate.model.Customer;

public class Application {
	private static SessionFactory factory = null;

	public static void main(String[] args) {

		System.out.println("============Set up Session Factory============");
		setUpSessionFactory();

		System.out.println("============Save Customers============");
		saveCustomers();

		System.out.println("============Show Customers============");
		showAllCustomers();

		System.out.println("============Update Customer - Peter with id = 1 & new age = 21============");
		updateCustomer(1, 21);

		System.out.println("============Delete Customer: Lauren with id = 3============");
		deleteCustomer(3);

		System.out.println("============Show Customers after Update & Delete============");
		// show all customer again - after update & delete
		showAllCustomers();

		shutdown();
	}

	public static void setUpSessionFactory() {
		// create sessionFactory
		try {
			factory = new Configuration().configure().addAnnotatedClass(Customer.class).buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static void shutdown() {
		factory.close();
	}

	public static void saveCustomers() {
		
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();

			// create customers
			Customer peter = new Customer("Peter", "Smith", 20);
			Customer mary = new Customer("Mary", "Taylor", 25);
			Customer lauren = new Customer("Lauren", "Taylor", 30);

			// save to database
			session.save(peter);
			session.save(mary);
			session.save(lauren);

			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void showAllCustomers() {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();
			List customers = session.createQuery("FROM Customer", Customer.class).list();
			customers.forEach(System.out::println);
			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void updateCustomer(int customerId, int newAge) {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();
			// update Peter: age = 21
			Customer cust = session.get(Customer.class, customerId);
			cust.setAge(newAge);
			session.update(cust);

			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		}
	}

	public static void deleteCustomer(int customerId) {
		Transaction tx = null;
		try(Session session = factory.openSession()) {
			tx = session.beginTransaction();

			// Employee employee =
			Customer cust = session.get(Customer.class, customerId);
			session.delete(cust);
			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.commit();
			}
		}
	}
}
5. Run & Check Results

– Run the main class Application.java, Logs:

...
Hibernate: drop table if exists customer
May 17, 2017 11:14:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@6622fc65] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table customer (id integer not null auto_increment, age integer not null, firstname varchar(255) not null, lastname varchar(255) not null, primary key (id)) engine=MyISAM
May 17, 2017 11:14:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@43b6123e] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
May 17, 2017 11:14:14 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@3300f4fd'
============Save Customers============
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
Hibernate: insert into customer (age, firstname, lastname) values (?, ?, ?)
============Show Customers============
May 17, 2017 11:14:14 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select customer0_.id as id1_0_, customer0_.age as age2_0_, customer0_.firstname as firstnam3_0_, customer0_.lastname as lastname4_0_ from customer customer0_
Customer info: id = 1, firstname = Peter, lastname = Smith, age = 20
Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25
Customer info: id = 3, firstname = Lauren, lastname = Taylor, age = 30
============Update Customer - Peter with id = 1 & new age = 21============
Hibernate: select customer0_.id as id1_0_0_, customer0_.age as age2_0_0_, customer0_.firstname as firstnam3_0_0_, customer0_.lastname as lastname4_0_0_ from customer customer0_ where customer0_.id=?
Hibernate: update customer set age=?, firstname=?, lastname=? where id=?
============Delete Customer: Lauren with id = 3============
Hibernate: select customer0_.id as id1_0_0_, customer0_.age as age2_0_0_, customer0_.firstname as firstnam3_0_0_, customer0_.lastname as lastname4_0_0_ from customer customer0_ where customer0_.id=?
Hibernate: delete from customer where id=?
============Show Customers after Update & Delete============
Hibernate: select customer0_.id as id1_0_, customer0_.age as age2_0_, customer0_.firstname as firstnam3_0_, customer0_.lastname as lastname4_0_ from customer customer0_
Customer info: id = 1, firstname = Peter, lastname = Smith, age = 21
Customer info: id = 2, firstname = Mary, lastname = Taylor, age = 25
...

– Customer’s records:

hibernate annotation - customer records

IV. Sourcecode

SpringHibernateAnnotations

0 0 votes
Article Rating
Subscribe
Notify of
guest
1.2K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments