April 23 2015

Hibernate enum mapping

Hibernate enum mapping  

This article will help you to map an Enumeration (enum) to a column in Hibernate. You can map columns wherever fixed values are allowed to enum.

Table


CREATE TABLE `student` (
 `STUDENT_ID` int(11) NOT NULL,
 `STUDENT_NAME` varchar(45) DEFAULT NULL,
 `FATHER_NAME` varchar(45) DEFAULT NULL,
 `DATE_OF_BIRTH` date DEFAULT NULL,
 `COURSE` varchar(45) DEFAULT NULL,
 `ACTIVE` int(2) DEFAULT NULL,
 PRIMARY KEY (`STUDENT_ID`)
) ;

The columns COURSE and ACTIVE can have fixed values. These two columns can be mapped to Enums.

Annotation

The datatype of the property should be configured to specific enum and the property or the getter method should be annotated with @Enumerated annotation Continue reading

March 18 2015

Hibernate Criteria Inner Join

Hibernate Criteria Inner Join

Hibernate features an intuitive,extensible criteria query API. Criteria provides a simplifed API to build queries dynamically at runtime. This is a very convenient approach if there is a variable number of conditions to be placed upon the result set.

The interface org.hibernate.Criteria representsa query against a particular class.

Criteria crit = session.createCriteria(Student.class);

List<Student> students = crit.list();

The above code queries for all the Student objects from the database.

Inner Join Continue reading

March 16 2015

org.hibernate.NonUniqueObjectException

org.hibernate.NonUniqueObjectException

NonUniqueObjectException will be thrown when you try to associate two different instances of the same class with same identifier in single session.In this case,hibernate is not able to decide which instance to persist.

org.hibernate.NonUniqueObjectException:

a different object with the same identifier value was already associated with the session

Example

In the below example,Student object with identifer 309 is loaded from database and is stored in student1.After session1.close(), student1 becomes detached object. Continue reading

March 9 2015

Difference between save and saveorupdate in hibernate

Difference between save and saveorupdate in hibernate

Save

Save method stores an object into the database. It will persist the transient instance, assigning a generated identifier if generator type is not assigned. It returns the id of the entity created.

saveOrUpdate

Calls either save() or update() on the basis of identifier. If identifier exists it will call update method otherwise it will call save method.

Continue reading