Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and focus on core java concepts. Generally, in hibernate, we use XML mapping files for converting our POJO classes data to database data and vice-versa. But using XML becomes a little confusing so, in replacement of using XML, we use annotations inside our POJO classes directly to declare the changes. Also using annotations inside out POJO classes makes things simple to remember and easy to use. Annotation is a powerful method of providing metadata for the database tables and also it gives brief information about the database table structure and also POJO classes simultaneously.
Setting up the Hibernate Annotations Project
It’s recommended to set up the Maven project for hibernate because it becomes easy to copy-paste dependency from the official Maven repository into your pom.xml.
Step 1: Create Maven Project (Eclipse)
Go to next and name a project and click to finish.
Step 2: Add the dependency to the pom.xml file
After setting up a maven project, by default, you get a POM.xml file which is a dependency file. POM stands for project object model, which allows us to add or remove dependency from 1 location.
The project structure and pom.xml should look like this. Now, add hibernate and MySQL dependency to use annotations to create a table and to use HQL(hibernate query language).
pom.xml file
XML
< modelVersion >4.0.0</ modelVersion >
< groupId >com.spring.hibernate</ groupId >
< artifactId >Spring-Hibernate</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< packaging >jar</ packaging >
< name >Spring-Hibernate</ name >
< properties >
< project.build.sourceEncoding >UTF-8</ project.build.sourceEncoding >
</ properties >
< dependencies >
< dependency >
< groupId >junit</ groupId >
< artifactId >junit</ artifactId >
< version >3.8.1</ version >
< scope >test</ scope >
</ dependency >
< dependency >
< groupId >org.hibernate</ groupId >
< artifactId >hibernate-core</ artifactId >
< version >5.6.14.Final</ version >
</ dependency >
< dependency >
< groupId >com.mysql</ groupId >
< artifactId >mysql-connector-j</ artifactId >
< version >8.0.31</ version >
</ dependency >
</ dependencies >
</ project >
|
Make sure you add dependency and it should look like the above file.
Step 3: Add hibernate.cfg.xml file for database parameters
We use the hibernate.cfg.xml file to provide all related database parameters like database username, password, localhost, etc. Make sure you make the hibernate.cfg.xml inside the resource folder
hibernate.cfg.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
< hibernate-configuration >
< session-factory >
< property name = "connection.driver_class" >com.mysql.jdbc.Driver</ property >
< property name = "connection.username" >root</ property >
< property name = "connection.password" >your password</ property >
< property name = "dialect" >org.hibernate.dialect.MySQL5Dialect</ property >
< property name = "hbm2ddl.auto" >update</ property >
< property name = "show_sql" >true</ property >
< mapping class = "com.spring.hibernate.Student" ></ mapping >
< mapping class = "com.spring.hibernate.Address" ></ mapping >
</ session-factory >
</ hibernate-configuration >
|
The file should look like above
Step 4: Add POJO and main classes for working with the functionality
Here are some annotations used in our POJO specifically for hibernate-
Annotations
|
Use of annotations
|
@Entity |
Used for declaring any POJO class as an entity for a database |
@Table |
Used to change table details, some of the attributes are-
- name – override the table name
- schema
- catalogue
- enforce unique constraints
|
@Id |
Used for declaring a primary key inside our POJO class |
@GeneratedValue |
Hibernate automatically generate the values with reference to the internal sequence and we don’t need to set the values manually. |
@Column |
It is used to specify column mappings. It means if in case we don’t need the name of the column that we declare in POJO but we need to refer to that entity you can change the name for the database table. Some attributes are-
- Name – We can change the name of the entity for the database
- length – the size of the column mostly used in strings
- unique – the column is marked for containing only unique values
- nullable – The column values should not be null. It’s marked as NOT
|
@Transient |
Tells the hibernate, not to add this particular column |
@Temporal |
This annotation is used to format the date for storing in the database |
@Lob |
Used to tell hibernate that it’s a large object and is not a simple object |
@OrderBy |
This annotation will tell hibernate to OrderBy as we do in SQL.
For example – we need to order by student firstname in ascending order
@OrderBy(“firstname asc”)
|
These are some annotations that are mostly used in order to work with hibernate.
Student.java (POJO class)
Java
package com.spring.hibernate;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table (name= "student" )
public class Student {
@Id
private int id;
private String firstName;
private String city;
public Student() {
super ();
}
public Student( int id, String firstName, String city) {
super ();
this .id = id;
this .firstName = firstName;
this .city = city;
}
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this .firstName = firstName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this .city = city;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", city=" + city + "]" ;
}
}
|
Address.java (POJO class)
Java
package com.spring.hibernate;
import java.util.Arrays;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@Table (name= "address" )
public class Address {
@Id
@GeneratedValue
@Column (name= "address_id" )
private int addid;
@Column (length= 50 )
private String street;
@Column (name= "city" )
private String city;
private boolean isOpen;
@Transient
private double x;
@Temporal (TemporalType.DATE)
private Date date;
@Lob
private byte [] images;
public Address( int addid, String street, String city, boolean isOpen, double x, Date date, byte [] images) {
super ();
this .addid = addid;
this .street = street;
this .city = city;
this .isOpen = isOpen;
this .x = x;
this .date = date;
this .images = images;
}
public Address() {
super ();
}
public int getAddid() {
return addid;
}
public void setAddid( int addid) {
this .addid = addid;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this .street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this .city = city;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen( boolean isOpen) {
this .isOpen = isOpen;
}
public double getX() {
return x;
}
public void setX( double x) {
this .x = x;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this .date = date;
}
public byte [] getImages() {
return images;
}
public void setImages( byte [] images) {
this .images = images;
}
@Override
public String toString() {
return "Address [addid=" + addid + ", street=" + street + ", city=" + city + ", isOpen=" + isOpen + ", x=" + x
+ ", date=" + date + ", images=" + Arrays.toString(images) + "]" ;
}
}
|
Main.java(Main Class)
Java
package com.spring.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App
{
public static void main( String[] args )
{
System.out.println( "Project Started" );
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Student student= new Student( 102 , "xyz" , "pune" );
System.out.println(student);
Address address= new Address();
address.setStreet( "JBRoad" );
address.setCity( "Pune" );
address.setDate( new Date());
address.setX( 34.8 );
address.setOpen( true );
Session session = factory.openSession();
Transaction tx=session.beginTransaction();
session.save(student);
session.save(address);
tx.commit();
session.close();
}
}
|
Output: