Example of the Hibernate Mapping with Annotation:
In the Hibernate we need the POJO class to make mapping with the database in any type of the mapping.
Create a table in the DataBase to store the object Using the MySql Database.
create table WORKER (
id INT NOT NULL auto_increment primary key,
first_name VARCHAR(30) default NULL,
last_name VARCHAR(30) default NULL,
salary INT default NULL,
);
Here we have mapping class HibernateMapping with annotation to map object with the WORKER table
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class HibernateMapping {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
In Hibernate Annotation tells us that @Id annotation is field and assumes that it access properties of object directly through fields at runtime. If in the Hibernate we placed the @Id annotation on the getId() method, then we enable access to properties through getter and setter methods by default.
@Entity
Annotation:
|
The EJB 3 annotations standard
Step 1: In the first step
we have to import javax.persistence
Step 2: When we used the @Entity annotation to
the HibernateMapping class it marked class to as an entity
bean, so it must have a no-argument constructor that is visible
with at least protected scope.
|
@Table
Annotation:
|
@Table annotation allows to
specify the details of the table that will be used to persist the
entity in the database.
@Table annotation provides four attributes allowing
override the name of the table, its catalogue, and its schema, and
enforce unique constraints on columns in the table.
|
@Id
and @GeneratedValue Annotations:
|
Each entity bean always will have
a primary key, which annotated on the class with the @Id
annotation. The primary key can be a single field or a
combination of multiple fields depending on table structure.
By default, @Id annotation will automatically determine
the most appropriate primary key generation strategy to be used
but can override this by applying the @GeneratedValue
annotation which takes two parameters strategy and generator,
that is default key generation strategy.
|
@Column
Annotation:
|
element maps the unique ID
attribute in class to the primary key of the database table.
Attribute name of the id element refers to the property in the
class and the column attribute refers to the column in the
database table. Attribute type holds the hibernate mapping type,
this mapping types will convert from Java to SQL data type.@Column
annotation is used to specify the details of the column to
which a field or property will be mapped. You can use column
annotation with the following most commonly used attributes:
Some common attribute are given
below:
Name attribute permits the
name of the column to be explicitly specified.
Length attribute permits
the size of the column used to map a value articularly for a
String value.
Nullable attribute permits
the column to be marked NOT NULL when the schema is generated.
Uniqueattribute permits the column to be marked as
containing only unique values.
|
Now we have to create Application Class:
create application class with the main() method to run the application. Because without main() method application can't run. In the application save the some WORKER details and then will apply CRUD operations on those records.
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageWorker {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new AnnotationConfiguration().configure().
//addPackage("com.abc") //add package if used.
addAnnotatedClass(HibernateMapping.class).buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageWorker MW = new ManageWorker();
/* Add few employee records in database */
Integer empID1 = MW.addWorker("aman", "Das", 1000);
Integer empID2 = MW.addWorker("puja", "Das", 5000);
Integer empID3 = MW.addWorker("Jra", "Paul", 10000);
/* List down all the worker */
MW.listEmployees();
/* Update worker's records */
MW.updateWORKER(empID1, 5000);
/* Delete an worker from the database */
MW.deleteWORKER(empID2);
/* List down new list of the worker */
ME.listWORKER();
}
/* Method to CREATE an worker in the database */
public Integer addWORKER(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer workerID = null;
try{
tx = session.beginTransaction();
WORKER worker = new WORKER();
WORKER.setFirstName(fname);
WORKER.setLastName(lname);
WORKER.setSalary(salary);
WORKERID = (Integer) session.save(WORKER);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return WORKERID;
}
/* Method to READ all the worker */
public void listWORKERS( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List WORKER = session.createQuery("FROM WORKER").list();
for (Iterator iterator = WORKER.iterator(); iterator.hasNext();){
WORKER worker = (WORKER) iterator.next();
System.out.print("First Name: " + worker.getFirstName());
System.out.print(" Last Name: " + worker.getLastName());
System.out.println(" Salary: " + worker.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an worker */
public void updateWorker(Integer WorkerID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee = (Worker)session.get(Worker.class, WorkerID);
employee.setSalary( salary );
session.update(worker);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an worker from the records */
public void deleteworker(Integer WorkerID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee = (Worker)session.get(Worker.class, WorkerID);
session.delete(worker);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Configure Database:
For configure data base we have to create hibernate.cfg.xml configuration file to define database related parameters.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_pro?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
</session-factory>
</hibernate-configuration>
After the doing this now we can compile for any exception:
Step 1. Before compiling the program we need to check the PATH and CLASS PATH is has been set or not.
Step 2. Delete Employee.hbm.xml mapping file from the path.
Step 3. Create Employee.java source file as shown above and compile it.
Step 4. Create ManageEmployee.java source file as shown above and compile it.
Step 5. Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in WORKER table.
after the run the application result will be come:
First Name: Aman Last Name: Ali Salary: 1000
First Name: puja Last Name: Das Salary: 5000
OutPut on the terminal with the database