- Hibernate — The simple Annotations
- Note :
- The simple Hibernate Annotations
- @Entity
- @Table
- @ID
- @GeneratedValue
- @Column
- @Temporal
- @Transient
- Adding annotations to a POJO/Entity class
- Adding the class that calls the Hibernate API
- Adding JARs
- Adding a configuration file
- Directory Structure of Hibernate Project
- Execution
Hibernate — The simple Annotations
Today we are going to understand how to use simple Hibernate annotations with our Model class(POJO class), which needs to be mapped to a database table and whose objects need to be persisted in the database using Hibernate.
As many of you must know that Hibernate is a middleware used for object-relational mapping(ORM) and for performing efficient object persistence.
In this article, we are going to create a Java class which will be mapped to a table in our database(Oracle Express Edition 10g) and its objects will be persisted, using the Hibernate.
Note :
In the upcoming example, We are going to create a Java class which will be mapped to a table in our database(Oracle Express Edition 10g). We are going to use some Hibernate Annotations, hence, there will be no need to create the mapping-resource with extension hbm.xml . And yes, one more thing, we are going to create this program in an Integrated Development Environment(IDE) , so you use any IDE of your choice.
The simple Hibernate Annotations
Note : Annotations are added on the top of an instance variable/property in a java class with which it is going to be associated or on the top of its getter method.
@Entity
@Entity (name = "USER_ADDRESS") class UserAddress
name is an attribute of @Entity Annotation and using this attribute we can specify a value/name to name our java class. Doing so, will push Hibernate to not map the class name to the table name in the database, it would rather take the name value of the @Table annotation. In the absence of @Table annotation, Hibernate would take the name value of @Entity annotation to name the database table.
@Table
@Entity @Table (name = "User_Info") class UserInfo
name is an attribute of @Table Annotation, which allows us to specify a value/name of the table in the database(which is going to created to map the Java class).
@ID
@Id @Column (name = "Roll_Number") private int rollNumber;
@Id annotation tells the hibernate to make this property a primary key in the database.
@GeneratedValue
@Id @Column (name = "Roll_Number") @GeneratedValue private int rollNumber;
This annotations allows the database to auto-increment the value of the primary key automatically. Hence, when this annotation is used, we don’t need to manually add the value of property which is made the primary key.
@Column
@Column (name = "First_Name") private String FirstName;
name is an attribute of @Column Annotation, which allows us to specify a name value of property, this name will be used to name the column in the database. If @Column annotation is used, Hibernate will not use the name of the property mentioned in a class to name the column in the database.
@Temporal
@Temporal(TemporalType.DATE) private Date createdOn;
@Temporal Annotation is used with the property of type java.util.date or java.util.Calendar.
- @Temporal(DATE)
Using the DATE property of @Temporal Annotation, you could save only the date value of the object without the time being saved with it.
@Transient
@Transient (name = "Comment") private String comment;
Adding annotations to a POJO/Entity class
- We are going to create a class that will contain all the Java code files representing our Model class(whose objects needs to be persisted) and the class that calls the Hibernate API and create an object-relational mapping(ORM) and perform object persistence.
This is a simple Java class whose objects needs to be persisted/saved, these objects are also known as Plain Old Java Objects(POJO) or Entity class. Some may even refer to such class whose objects needs to be persisted as the Model class.
package decodejava; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; @Entity @Table (name ="USER_INFO") public class UserInfo < @Id @Column (name = "ID") @GeneratedValue private int id; @Column (name = "First_Name") private String firstName; @Column (name = "Last_Name") private String lastName; @Temporal(DATE) private Date databaseCreatedOn; @Transient private String comment; public String getComment() < return comment; >public void setComment(String comment) < this.comment = comment; >public int getId() < return id; >public Date getDatabaseCreatedOn() < return databaseCreatedOn; >public void setDatabaseCreatedOn(Date databaseCreatedOn) < this.databaseCreatedOn = databaseCreatedOn; >public void setId(int id) < this.id = id; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >>
Adding the class that calls the Hibernate API
The Hiber class creates a Configuration object, used to configure the Hibernate. This is the first object we use when using the Hibernate. This object is used to specify the location of a configuration file and mapping document used by Hibernate. Using Configuration object we can create a SessionFactory object, which is eventually used to create a Session object to perform the object persistence operations.
Note : We will not need to set the Id value of each object, as it is automatically done by Hibernate’s sequence object by using @GeneratedValue annotation.
package decodejava; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Hiber < public static void main(String[] args) < SessionFactory sf= new Configuration().configure().buildSessionFactory(); Session session = sf.openSession(); //Creating the first object UserInfo ob1 = new UserInfo(); ob1.setFirstName("Paul"); ob1.setLastName("Walker"); ob1.setDatabaseCreatedOn(new Date()); ob1.setComment("One of the best movies - Fast and Furious"); //Creating the second object UserInfo ob2 = new UserInfo(); ob2.setFirstName("Leonardo"); ob2.setLastName("Dicaprio"); ob2.setDatabaseCreatedOn(new Date()); ob2.setComment("One of the best movies - Titanic"); //Creating the third object UserInfo ob3 = new UserInfo(); ob3.setFirstName("Johnny"); ob3.setLastName("Depp"); ob3.setDatabaseCreatedOn(new Date()); ob3.setComment("One of the best movies - What's Eating Gilbert's Grapes"); //Saving the objects session.beginTransaction(); session.save(ob1); //Saving the first object session.save(ob2); //Saving the second object session.save(ob3); //Saving the third object session.getTransaction().commit(); session.close(); //Retrieve and displaying the user details. session = sf.openSession(); session.beginTransaction(); ob1 = (UserInfo)session.get(UserInfo.class,1); ob2 = (UserInfo)session.get(UserInfo.class,2); ob3 = (UserInfo)session.get(UserInfo.class,3); System.out.println("Retrieving the saved objects"); //Retrieving details of the first user. System.out.println("First User"); System.out.println("Id : " + ob1.getId()); System.out.println("First Name : " + ob1.getFirstName()); System.out.println("Last Name : " +ob1.getLastName()); System.out.println("Datebase created : " + ob1.getDatabaseCreatedOn()); //Retrieving details of the second user. System.out.println("Second User"); System.out.println("Id : " + ob2.getId()); System.out.println("First Name : " + ob2.getFirstName()); System.out.println("Last Name : " +ob2.getLastName()); System.out.println("Datebase created : " + ob2.getDatabaseCreatedOn()); //Retrieving details of the third user. System.out.println("Third User"); System.out.println("Id : " + ob3.getId()); System.out.println("First Name : " + ob3.getFirstName()); System.out.println("Last Name : " +ob3.getLastName()); System.out.println("Datebase created : " + ob3.getDatabaseCreatedOn()); session.getTransaction().commit(); //closing the session session.close(); >>
Adding JARs
- We are going to add some JARs files to the build path of our Java project. These JARs make the Hibernate work with our database using a specific JDBC Driver for our particular database.
All these JARs are included in the folder named required(within our Hibernate installation folder). So, we need to add all the JARs in the required to our build path of our Java project.
Adding a configuration file
- Next, we are going to add a configuration file to our project.
This configuration document ends with an extension .cfg.xml, and it is named as hibernate.cfg.xml.
- A database to which Hibernate connects to perform object-relational mapping and object persistence.
- The JDBC driver class for our specific database, used by the Hibernate to connect to the database.
- The username and password of database, using which the Hibernate connects to the database.
- An SQL Dialect, used by the Hibernate to instruct the database.
- A Entity/POJO class which will be mapped to a database table by Hibernate.
- A command to echo all the SQL commands which are executed by the Hibernate on stdout.
- The mapping entity class, used by Hibernate to correctly map the class to a database table.
oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@localhost:1521:XE system promila21 1 org.hibernate.dialect.Oracle10gDialect org.hibernate.cache.internal.NoCacheProvider true create
Directory Structure of Hibernate Project
The picture above depicts how and where to arrange POJO/Entity(.java) file and the other the class(that calls the hibernate into action) in a specific directory structure.
- This project folder contains the main package of our project i.e. decodejava, which contains POJO/Entity class file i.e. UserInfo.java and the class that calls the hibernate into action i.e. Hiber.java.
Execution
Finally, after executing Hiber class, you will get the following output within the Console window of your IDE or Command Prompt, as shown below.
Hibernate: create sequence hibernate_sequence start with 1 increment by 1 Hibernate: create table USER_INFO (ID number(10,0) not null, databaseCreatedOn date, First_Name varchar2(255 char), Last_Name varchar2(255 char), primary key (ID)) Hibernate: select hibernate_sequence.nextval from dual Hibernate: select hibernate_sequence.nextval from dual Hibernate: select hibernate_sequence.nextval from dual Hibernate: insert into USER_INFO (databaseCreatedOn, First_Name, Last_Name, ID) values (?, ?, ?, ?) Hibernate: insert into USER_INFO (databaseCreatedOn, First_Name, Last_Name, ID) values (?, ?, ?, ?) Hibernate: insert into USER_INFO (databaseCreatedOn, First_Name, Last_Name, ID) values (?, ?, ?, ?) Hibernate: select userinfo0_.ID as ID1_0_0_, userinfo0_.databaseCreatedOn as databaseCreatedOn2_0_0_, userinfo0_.First_Name as First_Name3_0_0_, userinfo0_.Last_Name as Last_Name4_0_0_ from USER_INFO userinfo0_ where userinfo0_.ID=? Hibernate: select userinfo0_.ID as ID1_0_0_, userinfo0_.databaseCreatedOn as databaseCreatedOn2_0_0_, userinfo0_.First_Name as First_Name3_0_0_, userinfo0_.Last_Name as Last_Name4_0_0_ from USER_INFO userinfo0_ where userinfo0_.ID=? Hibernate: select userinfo0_.ID as ID1_0_0_, userinfo0_.databaseCreatedOn as databaseCreatedOn2_0_0_, userinfo0_.First_Name as First_Name3_0_0_, userinfo0_.Last_Name as Last_Name4_0_0_ from USER_INFO userinfo0_ where userinfo0_.ID=? Retrieving the saved objects First User Id : 1 First Name : Paul Last Name : Walker Datebase created : 2018-05-18 Second User Id : 2 First Name : Leonardo Last Name : Dicaprio Datebase created : 2018-05-18 Third User Id : 3 First Name : Johnny Last Name : Depp Datebase created : 2018-05-18
This output shows you that Hibernate has used its sequence object to generate the value of each primary key automatically plus all the SQL commands executed by the Hibernate within the database to map the Java class to a database table and perform all the activities of saving, modifying, deleting and retrieving the objects of UserInfo.