Difference between save and persist method in Hibernate
1) First difference
between save and persist is there return type. Similar to save method persist
also INSERT records into database but return type of persist is void while
return type of save is Serializable object.
2) Another difference
between persist and save is that both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value
will be assigned to the persistent instance immediately, the assignment might
happen at flush time.
3) One more thing which
differentiate persist and save method in Hibernate is that is there behavior on
outside of transaction boundaries. persist() method guarantees that
it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the
same, it returns an identifier, and if an INSERT has to be executed to get the
identifier (e.g. "identity" generator), this INSERT happens
immediately, no matter if you are inside or outside of a transaction.
4) Fourth difference between save and persist method in Hibernate is related to previous difference on save vs persist. Because of its above behavior of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
--------------------------------------------------------------------------------------------------------------------
Both save() and persist() are used to insert a new entity in the database. You're calling them on entities that already exist in the database. So they do nothing.
The main difference between them is that save() is Hibernate-proprietary, whereas persist() is a standard JPA method. Additionally, save() is guaranteed to assign and return an ID for the entity,
whereas persist() is not.
-----------------------------------------------------------------------------------
-------------------------------------
Difference between save and persist method in Hibernate
First : difference between save and persist is there return type. The return type of persist method is void while return type of save method is Serializable object. But bot of them also INSERT records into database
Second :Another difference between persist and save is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.
Third :difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.
Fourth : difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.
Fifth : difference between save and persist method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.
That’s it on the Difference between save saveOrUpdate and persist in Hibernate.
-------------------------------------
down vote
|
By default,
Hibernate ships with the ability to obtain a data source implementation (
javax.sql.DataSource ) from JNDI by setting the properties appropriately:
The Default JNDI Connection Pool
maxsize is -No Maximum Size
Here you can find the default values
of JNDI pool.
In order to get Efficient performance
You should use a third party
pool for best performance and
stability.
If you are using an application
server, you may wish to use the built-in pool (typically a connection is
obtaining using JNDI). If you can't or don't wish to use your application
server's built-in connection pool, Hibernate supports several other
connection pools such as
· c3p0
· Apache
DBCP
· Proxool
-----------------------------------------------------------------------------------------------------------
save
Save method stores
an object into
the database. It will Persist the given transient instance, first assigning a
generated identifier. It returns the id of
the entity created.
Whereas,
SaveOrUpdate()
Calls either save() or update() on
the basis of identifier exists or not. e.g if identifier exists, save() will
be called or else update() will
be called.
There are many more like persist(),
merge(), saveOrUpdateCopy(). Almost all are same giving slight different
functionality and usability.
-------------------------------------------------------------------------------------------------------------
update() is
used to attach a detached entity to the session.
saveOrUpdate() is
used to either save or update an entity depending on the state (new or
detached) of the entity.
Note that you don't need to call any
method of the session to modify an attached entity: doing
User user1
=(User)session.load(User.class,Integer.valueOf(1));
user1.setCompany("Company3");
is sufficient to have the company of
the user 1 updated in the database. Hibernate detects the changes made on
attached entities, and saves them in the database automatically.
SaveSave
method stores an object into the database. That means it insert an entry if
the identifier doesn’t exist, else it will throw error. If the primary key
already present in the table, it cannot be inserted.
updateUpdate
method in the hibernate is used for updating the object using identifier. If
the identifier is missing or doesn’t exist, it will throw exception.
saveOrUpdate This
method calls save() or update() based on the operation. If the identifier
exists, it will call update method else the save method will be called.
saveOrUpdate() method does the following: If the object is already persistent
in the current session, it do nothing If another object associated with the
session has the same identifier, throw an exception to the caller If the
object has no identifier property, save() the object If the object’s
identifier has the value assigned to a newly instantiated object, save() the
object - See more at: http://www.javabeat.net/difference-between-hibernates-saveupdate-and-saveorupdate-methods/#sthash.ZwqNlWXH.dpuf
---------------------------------------------------------------------------------------------------------
saveOrUpdate -
inserts a row if it does not exist in a database or update it if it does
exist.
save -
always try to insert a row into a database.
update -
always try to update a row in a database. Example of using saveOrUpdate.
Assume that you developed the program
that gets the information about user visits for current day from Google
Analytics and saves it into your database.
If there are no information about the
day in your database, method saveOrUpdate will
insert the data, otherwise it will update existing data.
--------------------------------------------------------------------------------------------------------------
difference between Save() and
Persist()
I did some mock testing to record the
difference between Save() and Persist().
Sounds like both these methods
behaves same when dealing with Transient Entity but differ when dealing with
Detached Entity.
For the below example , take
EmployeeVehicle as an Entity with PK as vehicleId which is a generated value
and vehicleName as one of its property .
Example 1 : Dealing with Transient
Object
Sessionsession=factory.openSession();
session.beginTransaction();
EmployeeVehicle entity
=newEmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();
Result : select nextval ('hibernate_sequence') //
This is for vehicle Id generated : 36
insert
intoEmployee_Vehicle(Vehicle_Name,Vehicle_Id) values (Honda,36)
Repeat the same withusing
persist(entity)and will result the same withnewId( say 37,honda);
Example 2 : Dealing with Detached
Object
// Session 1
// Get the previously saved Vehicle
Entity
Sessionsession=factory.openSession();
session.beginTransaction();
EmployeeVehicle entity
=(EmployeeVehicle)session.get(EmployeeVehicle.class,36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity
obtained in previous session is a detached object and now we will try to save
/ persist it
(i)UsingSave() to persist a detached
object
Session session2 =factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();
Result : You might be expecting the
Vehicle with id : 36 obtained in previous session is updated with name as
"Toyota" . But what happens is that a new entity is saved in the DB
with new Id generated for and Name as "Toyota"
selectnextval('hibernate_sequence')
insert intoEmployee_Vehicle(Vehicle_Name,Vehicle_Id) values (Toyota,39)
(ii)UsingPersist() to persist a
detached object
// Session 1
Sessionsession=factory.openSession();
session.beginTransaction();
EmployeeVehicle entity
=(EmployeeVehicle)session.get(EmployeeVehicle.class,36);
session.close();
// Session 2 // Here in Session 2 ,
vehicle entity obtained in previous session is a detached object and now we
will try to save / persist it (i) Using persist() to persist a detached
object
Session session2 =factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();
Result : Exception being thrown :
detached entity passed to persist.
NonUniqueObjectException
So, it is always better to use
Persist() rather than Save() as save has to be carefully used when dealing
with session and transcation .
Persist():
Save():
|
persist() is well defined. It makes a transient instance persistent.
However, it doesn't guarantee that the identifier value will be assigned to the
persistent instance immediately, the assignment might happen at flush time. The
spec doesn't say that, which is the problem I have with persist().
persist() also guarantees that it will not execute an INSERT statement if it
is called outside of transaction boundaries. This is useful in long-running
conversations with an extended Session/persistence context.
A method like persist() is required.
save() does not guarantee the same, it returns an identifier, and if an
INSERT has to be executed to get the identifier (e.g. "identity"
generator, not "sequence"), this INSERT happens immediately, no
matter if you are inside or outside of a transaction. This is not good in a
long-running conversation with an extended Session/persistence context.
------------------------------------------------------------------------------------------------------------------------
These were some differences
between save, saveOrUpdate and persist method of Hibernate. All three
method are related to saving Object into database but there behavior are quite
different. Knowledge
of save, persist and saveOrUpdate not only helps to
decide better use of Hibernate API but also help you to do well in Hibernate
interviews.
Save()
1. Returns generated Id after saving. Its Serializable return type.
2. Saves the value to DB immediately and keeps
track of the entity until the end of the session(I have tried to change the
entity values outside of the transaction, it does not show any effect when
session commits)
3. Does not save the changes to the db outside of
the transaction.
4. Assigns the generated id to the entity you are
persisting
5. Session.save() for a detached object will
create a new row in the table.
Persist()
1. Does not returns generated Id after saving.
Its void return type.
2. Saves the value to DB immediately and keeps
track of the entity until the end of the session.(I have tried to change the
entity values outside of the transaction, it does not show any effect when
session commits)
3. Does not save the changes to the db outside of
the transaction.
4. Assigns the generated id to
the entity you are persisting
5. session.persist() for a detached object will throw PersistentObjectException as it is
not allowed.
11) What is the difference between update and
merge method?
No.
|
update()
method
|
merge()
method
|
1)
|
Update means to edit something.
|
Merge means to combine something.
|
2)
|
update() should be used if session doesn't contain an
already persistent state with same id. It means update should be used inside
the session only. After closing the session it will throw error.
|
merge() should be used if you don't know
the state of the session, means
you want to make modification at any time.
|
The
differences between update() and merge() methods are given below.
Let's try to understand the
difference by the example given below:
1. SessionFactory factory = cfg.buildSessionFactory();
2. Session session1 = factory.openSession();
3.
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing id of employee
4. session1.close();
5. e1.setSalary(70000);
6. Session session2 = factory.openSession();
7.
Employee e2 = (Employee) session1.get(Employee.class, Integer.valueOf(101));//passing same id
8. Transaction tx=session2.beginTransaction();
9. session2.merge(e1);
10. tx.commit();
11. session2.close();
After closing session1, e1
is in detached state. It will not be in session1 cache. So if you call update()
method, it will throw an error.
7) What is Session?
It maintains a connection
between hibernate application and database.
It provides methods to
store, update, delete or fetch data from the database such as persist(),
update(), delete(), load(), get() etc.
It is a factory of Query,
Criteria and Transaction i.e. it provides factory methods to return these
instances.
SESSION
in HIBERNATE
The session objects should not be kept open for a long time
because they are not usually thread safe and they should be created and
destroyed them as needed. The main function of the Session is to offer create,
read and delete operations for instances of mapped entity classes. Instances
may exist in one of the following three states at a given point in time:
1) transient: A new instance of a
persistent class which is not associated with a Session and has no
representation in the database and no identifier value is considered transient
by Hibernate.
2) persistent: You can make a transient
instance persistent by associating it with a Session. A persistent instance has
a representation in the database, an identifier value and is associated with a
Session.
3) detached: Once we close the
Hibernate Session, the persistent instance will become a detached instance.
A Session instance is serializable if its persistent classes are
serializable. A typical transaction should use the following idiom:
Session session =
factory.openSession();
Transaction tx = null;
try {
tx =
session.beginTransaction();
// do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null)
tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
If the Session throws an
exception, the transaction must be rolled back and the session must be
discarded.
8) Is Session a thread-safe object?
No, Session is not a
thread-safe object, many threads can't access it simultaneously. In other
words, you cannot share it between threads.
12) What are the states of object in hibernate?
There are 3 states of object (instance) in hibernate.
1. Transient: The object is in transient state if it is just created but has
no primary key (identifier) and not associated with session.
2. Persistent: The object is in persistent state if session is open, and you
just saved the instance in the database or retrieved the instance from the
database.
3. Detached: The object is in detached state if session is closed. After
detached state, object comes to persistent state if you call lock() or update()
method.
1. Transient State:
A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:
A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:
1. UserDetail user = new UserDetail();
2. user.setUserName("Dinesh Rajput");
3. // user is in a transient state
2.
Persistent State:
A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:
A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:
1. Long id = (Long) session.save(user);
2. // user is now in a persistent state
3.
Detached State:
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to aSession anymore (but can still be modified and reattached to a new Session later though).
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to aSession anymore (but can still be modified and reattached to a new Session later though).
1. session.close();
2. //user in detached state
Difference between Transient and Detached
States:
Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database. Once the last reference is lost, that means the object itself is lost. And of course, garbage collected. The commits and rollbacks will have no effects on these objects. They can become into persistent objects through the save method calls of Session object.
The detached object have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session was closed. Since then, the change may be done in the database which makes this object stale. The detached object can be reattached after certain time to another object in order to become persistent again.
Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database. Once the last reference is lost, that means the object itself is lost. And of course, garbage collected. The commits and rollbacks will have no effects on these objects. They can become into persistent objects through the save method calls of Session object.
The detached object have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session was closed. Since then, the change may be done in the database which makes this object stale. The detached object can be reattached after certain time to another object in order to become persistent again.
4) What are the core interfaces of Hibernate?
The core interfaces of
Hibernate framework are:
- Configuration
- SessionFactory
- Session
- Query
- Criteria
- Transaction
Transient & Persistent
states:
· When ever an object of a pojo class is created
then it will be in the Transient
state
· When the object is in a Transient state
it doesn’t represent any row of the database, i mean not associated with any Session object, if we speak more we can say no relation with the
database its just an normal object
· If we modify the data of a pojo class object,
when it is in transient state then it doesn’t effect on the database table
· When the object is in persistent state, then
it represent one row of the database, if the object is in persistent state then it is associated with the unique Session
· if we want to move an object from persistent to detached state, we need to do either closing that
session or need to clear the cache of the session
· if we want to move an object from persistent state into transient state then we need to delete that object
permanently from the database.
·
package com.sdnext.hibernate.tutorial;
·
·
import org.hibernate.Session;
·
import org.hibernate.SessionFactory;
·
import org.hibernate.cfg.AnnotationConfiguration;
·
·
import com.sdnext.hibernate.tutorial.dto.UserDetails;
·
·
public class HibernateTestDemo {
·
/**
·
* @param args
·
*/
·
public static void main(String[] args)
·
{
·
UserDetails userDetails = new UserDetails();
·
userDetails.setUserName("Dinesh Rajput");
·
userDetails.setAddress("Noida City");
·
//Here 'userDetails' is TRANSIENT object
·
·
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
·
Session session = sessionFactory.openSession();
·
session.beginTransaction();
·
·
session.save(userDetails);
·
//Here 'userDetails' is PERSISTENT object
·
userDetails.setUserName("User Updated after session close");
·
session.getTransaction().commit();
·
session.close();
·
//Here 'userDetails' is DETACHED object
·
}
·
}
13) What are the inheritance mapping strategies?
There are 3 ways of
inheritance mapping in hibernate.
1. Table per hierarchy
2. Table per concrete class
3. Table per subclass
16) How many types of association mapping are possible in
hibernate?
There can be 4 types of
association mapping in hibernate.
1. One to One
2. One to Many
3. Many to One
4. Many to Many
17) Is it possible to perform collection mapping with One-to-One
and Many-to-One?
No, collection mapping can
only be performed with One-to-Many and Many-to-Many
18) What is lazy loading in hibernate?
Lazy loading in hibernate
improves the performance. It loads the child objects on demand.
Since Hibernate 3, lazy
loading is enabled by default, you don't need to do lazy="true". It
means not to load the child objects when parent is loaded.
19) What is HQL (Hibernate Query Language)?
Hibernate Query Language is
known as an object oriented query language. It is like structured query
language (SQL).
The main advantage of HQL
over SQL is:
1. You don't need to learn SQL
2. Database independent
3. Simple to write query
5) What is SessionFactory?
SessionFactory provides the
instance of Session. It is a factory of Session. It holds the data of second
level cache that is not enabled by default.
8) Is Session a thread-safe object?
No, Session is not a thread-safe
object, many threads can't access it simultaneously. In other words, you cannot
share it between threads.
6) Is SessionFactory a thread-safe object?
Yes, SessionFactory is a
thread-safe object, many threads can access it simultaneously.
Hibernate Transaction Management Example
A transaction simply represents a unit of work.
In such case, if one step fails, the whole transaction fails (which is termed
as atomicity). A transaction can be described by ACID properties (Atomicity,
Consistency, Isolation and Durability).
Hibernate - Criteria Queries
Hibernate provides alternate ways of manipulating objects and in
turn data available in RDBMS tables. One of the methods is Criteria API which
allows you to build up a criteria query object programmatically where you can
apply filtration rules and logical conditions.
The Hibernate Session interface provides createCriteria() method
which can be used to create a Criteria object that returns
instances of the persistence object's class when your application executes a
criteria query.
Following is the simplest example of a criteria query is one which
will simply return every object that corresponds to the Employee class.
Criteria cr = session.createCriteria(Employee.class);
List results = cr.list()
Restrictions
with Criteria:
You can use add() method available for Criteria object
to add restriction for a criteria query. Following is the example to add a
restriction to return the records with salary is equal to 2000:
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
Following are the few more examples covering different scenarios
and can be used as per requirement:
Criteria cr = session.createCriteria(Employee.class);
//
To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));
//
To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));
//
To get records having fistName starting with zara
cr.add(Restrictions.like("firstName", "zara%"));
//
Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));
//
To get records having salary in between 1000 and 2000
cr.add(Restrictions.between("salary", 1000, 2000));
//
To check if the given property is null
cr.add(Restrictions.isNull("salary"));
//
To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));
//
To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));
//
To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));
You can create AND or OR conditions using LogicalExpression
restrictions as follows:
Criteria cr = session.createCriteria(Employee.class);
Criterion salary = Restrictions.gt("salary", 2000);
Criterion name = Restrictions.ilike("firstNname","zara%");
//
To get records matching with OR conditions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );
//
To get records matching with AND conditions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );
List results = cr.list();
Though all the above conditions can be used directly with HQL as
explained in previous tutorial.
1.1 Pagination using Criteria:
There are two methods of the Criteria interface for pagination.
S.N.
|
Method &
Description
|
1
|
public Criteria
setFirstResult(int firstResult)
This method takes an integer that
represents the first row in your result set, starting with row 0.
|
2
|
public Criteria
setMaxResults(int maxResults)
This method tells Hibernate to
retrieve a fixed number maxResultsof objects.
|
Using above two methods together, we can construct a paging
component in our web or Swing application. Following is the example which you
can extend to fetch 10 rows at a time:
Criteria cr = session.createCriteria(Employee.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();
Sorting the Results:
The Criteria API provides the org.hibernate.criterion.Order class
to sort your result set in either ascending or descending order, according to
one of your object's properties. This example demonstrates how you would use
the Order class to sort the result set:
Criteria cr = session.createCriteria(Employee.class);
//
To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));
//
To sort records in descening order
crit.addOrder(Order.desc("salary"));
//
To sort records in ascending order
crit.addOrder(Order.asc("salary"));
List results = cr.list();
Projections & Aggregations:
The Criteria API provides the org.hibernate.criterion.Projections class
which can be used to get average, maximum or minimum of the property values.
The Projections class is similar to the Restrictions class in that it provides
several static factory methods for obtaining Projection instances.
Following are the few examples covering different scenarios and
can be used as per requirement:
Criteria cr = session.createCriteria(Employee.class);
//
To get total row count.
cr.setProjection(Projections.rowCount());
//
To get average of a property.
cr.setProjection(Projections.avg("salary"));
//
To get distinct count of a property.
cr.setProjection(Projections.countDistinct("firstName"));
//
To get maximum of a property.
cr.setProjection(Projections.max("salary"));
//
To get minimum of a property.
cr.setProjection(Projections.min("salary"));
//
To get sum of a property.
cr.setProjection(Projections.sum("salary"));
1.2 Criteria Queries Example:
Consider the following POJO class:
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
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;
}
}
Let us create the following EMPLOYEE table to store Employee
objects:
create
table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default
NULL,
PRIMARY KEY (id)
);
Following will be mapping file.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE
hibernate-mapping PUBLIC
"-//Hibernate/Hibernate
Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main()
method to run the application where we will use Criteria queries:
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.SessionFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create
sessionFactory object."
+ ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records
in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 5000);
Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);
/* List down all the
employees */
ME.listEmployees();
/* Print Total employee's
count */
ME.countEmployee();
/* Print Toatl salary */
ME.totalSalary();
}
/* Method to CREATE an
employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all
the employees having salary more than 2000 */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// Add restriction.
cr.add(Restrictions.gt("salary", 2000));
List employees = cr.list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name:
"
+ employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to print total
number of records */
public void countEmployee(){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// To get total row count.
cr.setProjection(Projections.rowCount());
List rowCount = cr.list();
System.out.println("Total Coint: " + rowCount.get(0) );
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to print sum of
salaries */
public void totalSalary(){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// To get total salary.
cr.setProjection(Projections.sum("salary"));
List totalSalary = cr.list();
System.out.println("Total Salary: " + totalSalary.get(0) );
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Compilation and Execution:
Here are the steps to compile and run the above mentioned
application. Make sure you have set PATH and CLASSPATH appropriately before
proceeding for the compilation and execution.
· Create hibernate.cfg.xml configuration file as explained in
configuration chapter.
· Create Employee.hbm.xml mapping file as shown above.
· Create Employee.java source file as shown above and compile it.
· Create ManageEmployee.java source file as shown above and compile
it.
· Execute ManageEmployee binary to run the program.
You would get following result, and records would be created in
EMPLOYEE table.
$java
ManageEmployee
.......VARIOUS LOG MESSAGES WILL
DISPLAY HERE........
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 5000
First Name: Mohd Last Name: Yasee Salary: 3000
Total Coint: 4
Total Salary: 15000
If you check your EMPLOYEE table, it should have following records:
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 14 | Zara
| Ali
| 2000 |
| 15 | Daisy
| Das
| 5000 |
| 16 | John
| Paul
| 5000 |
| 17 | Mohd
| Yasee | 3000 |
+----+------------+-----------+--------+
4 rows in set (0.00 sec)
mysql>
No comments:
Post a Comment