Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Friday, July 22, 2011

Incorrect Order of SQL execution within a Spring Hibernate Transaction

Recently I faced a strange issue when trying to insert proper data into table ,it was halting with Unique key Constraint Exception.In a transaction I had to read a record and update the Unique Key fields and in the next step insert a record .The record inserted should have the same Unique Key values as the record read from the table.The sequence was a simple read,update and insert a new record.Was baffled when this sequence continuous threw a Unique Key Constraint.When I removed the UK constraint from the table,the records were updated and inserted as required.

On checking on the hibernate log found that the insert was fired before the update .I tried to disable the Spring transaction and then the order of execution was correct.
Looks like the order of SQl execution is not guaranteed within a transaction.To solve this issue one of the following needs to be done after the update and before the insert
1.call hibernateTemplate.flush() or
2.call hibernateTemplate.refresh() or
3.again read the record from table ,this internally calls the flush.

Friday, July 2, 2010

Hibernate Criteria Sample Implementation

The Criteria interface in Hibernate is used to create and execute object-oriented queries.
The following are some commonly used criterion.
(i) To query based on simple search criteria like Employee Type Permanent and Confirmation Date less than Request Date
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.eq( "empType", 'P' ),
Restrictions.and( Restrictions.isNotNull( "confirmationDate" ),
Restrictions.le( "confirmationDate",
requestDate ) )
};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(ii) To Retrieve values between

Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.between( "joiningDate", startDate,endDate )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(iii) Using In Clause
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
List result=criteria.list( );

(iv) To find Record Count.
Criteria criteria = session.createCriteria( Emp.class );
criteria.setProjection(Projections.rowCount());
result=criteria.list( );
if ((null != result) && (!result.isEmpty())) {
Integer rowCount = (Integer) result.get(0);
}

(v) Returning 'n' columns from the Entity List based on Search Criteria
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
criteria.setProjection( Projections.projectionList( )
.add( Projections.property( fieldName1 )) .add( Projections.property( fieldName2 ) ) );
List result=criteria.list( );

(vi) Return Result based on descending order
Criteria criteria = session.createCriteria( Emp.class );
Criterion[] criterions = new Criterion[] {
Restrictions.in( "empType",new Object[]{'P','C','R' )};
for ( Criterion criterion : criterions ) {
criteria.add( criterion );
}
crietrai.addOrder( Order.desc("empName") )
List result=criteria.list( );

Tuesday, May 18, 2010

Named Queries

NamedQuery feature in Hibernate allows Queries to added in Entity or Mapping Documents.The Queries can be of HQL or SQL type.NamedQuery structure has a name and query part.The name identifies the Query and should be unique in the context.If there are multiple named queries for an Entity,it can be specified within a NamedQueries construct.
@NamedQueries({

@NamedQuery(
name = "findEmpByAge",
query = "from emp e where e.age>?"
),

@NamedQuery(
name = "findEmpByRole",
query = "from emp e where e.role=?"
)
})

Adding additional fields in @Entity Class

In the Entity class, the persistent fields are mapped with @Column construct.But there could be some computed or other fields which are not in the table but are required in the Entity class.Adding these additional fields in the entity would give rise to Invalid Identifier Exception.To avoid this,these additional fields can be used with @Transient construct.When the fields are marked as Transient ,they are not associated with the Session Factory and their instances would be destroyed by the GC.

Thursday, February 18, 2010

Hibernate Sequence Generator

Hibernate generator element generates the primary key for new record. This is used in conjunction with the Id element. Hibernate provides about 11 types of generator .Among these the Sequence generator uses the Sequence from the Database and returns identifier value of type long,short or int.

To use the Sequence from the database,need to map the field for Id, and specify the Generation Type as Sequence. By default the sequence generator provides values that are incremented in counts of 50,this can be overridden by specifying the allocationSize

@Entity( name = "EmployeeEntity" )
@SequenceGenerator( name = "id_sequence", allocationSize = 1, sequenceName = "SEQ_EMP_ID" )
@Table( name = "T_EMP_MASTER" )
public class EmployeeEntity implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "id_sequence" )
@Column( name = "emp_id" )
private Long empId;
@Column(name="firstName")
private String firstName;
@Column(name="lastName")
private String lastName;
//Getters and Setters
}