Archive for the ‘Uncategorized’ Category


Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

HQL is extremely simple to learn and use, and the code is always self-explanatory.

1. HQL Select Query Example

Retrieve a stock data where stock code is “7277″.

Query query = session.createQuery(“from Stock where stockCode = :code “);

query.setParameter(“code”, “7277”);

List list = query.list();

Query query = session.createQuery(“from Stock where stockCode = ‘7277’ “);

List list = query.list();

 2. HQL Update Query Example

Update a stock name to “DIALOG1″ where stock code is “7277″.

Query query = session.createQuery("update Stock set stockName = :stockName" +
                                                 " where stockCode = :stockCode");
query.setParameter("stockName", "DIALOG1");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
Query query = session.createQuery("update Stock set stockName = 'DIALOG2'" +
                                                 " where stockCode = '7277'");
int result = query.executeUpdate();

 

3. HQL Delete Query Example

Delete a stock where stock code is “7277″.

Query query = session.createQuery("delete Stock where stockCode = :stockCode");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
Query query = session.createQuery("delete Stock where stockCode = '7277'");
int result = query.executeUpdate();

4. HQL Insert Query Example

In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table. For example

"insert into Object (id, name) select oo.id, oo.name from OtherObject oo";

Insert a stock record from another backup_stock table. This can also called bulk-insert statement.

Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
                                     "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

The query.executeUpdate() will return how many number of record has been inserted, updated or deleted.

Hibernate parameter binding examples

There are two ways to parameter binding : named parameters or positional.

1. Named parameters

This is the most common and user friendly way. It use colon followed by a parameter name (:example) to define a named parameter. See examples…

Example 1 – setParameter

The setParameter is smart enough to discover the parameter data type for you.

String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setParameter("stockCode", "7277")
.list();
Example 2 – setString

You can use setString to tell Hibernate this parameter date type is String.

String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setString("stockCode", "7277")
.list();
Example 3 – setProperties

This feature is great ! You can pass an object into the parameter binding. Hibernate will automatic check the object’s properties and match with the colon parameter.

Stock stock = new Stock();
stock.setStockCode("7277");
String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setProperties(stock)
.list();

 

2. Positional parameters

It’s use question mark (?) to define a named parameter, and you have to set your parameter according to the position sequence. See example…

String hql = "from Stock s where s.stockCode = ? and s.stockName = ?";
List result = session.createQuery(hql)
.setString(0, "7277")
.setParameter(1, "DIALOG")
.list();

This approach is not support the setProperties function. In addition, it’s vulnerable to easy breakage because every change of the position of the bind parameters requires a change to the parameter binding code.

String hql = "from Stock s where s.stockName = ? and s.stockCode = ?";
List result = session.createQuery(hql)
.setParameter(0, "DIALOG")
.setString(1, "7277")
.list();

 

 

Advertisements

Criteria-Examples

Posted: April 11, 2012 in Uncategorized

Criteria API

 

  1. 1.     Criteria
  2. 2.     Restrictions
  3. 3.     Expressions
  4. 4.     Projections 

Creating Criteria:

 SessionFactory sessionFactory = 

new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Criteria crit = session.createCriteria(Java Class.class);//criteria creation

List results = crit.list();

Method Description
add                                            The Add method adds a Criterion to constrain the result to be retrieved.
addOrder Add an Order to the result set.
createalias Join an association, assigning an alias to the joined entity.
createCriteria This method is used to create a new Criteria “rooted” at the associated entity.
setFetchSize This method is used a set a fetch size for underlying JDBC query.
setFirstResult This method used to be set the first result to be retrieved.
setMaxResults This method used to be set a limit upon the number of objects to be retrieved.
uniqueResult This method used to instruct the hibernate fetch and return the unique records from database.

  

Criteria interface Methods description:

  1. 1.     Add() & addOrder() :

Criteria criteria = session.createCriteria(Event.class);

criteria.add(Restrictions.between(“duration”,

new Integer(60), new Integer(90) );

criteria.add( Restrictions.like(“name”, “Presen%”) );

criteria.addOrder( Order.asc(“name”) );

  1. Create criteria(): Used for Association

By navigating associations using creteCriteria() you  can specify constraints upon related entities:

List cats = sess.createCriteria(Cat.class)

.add(Restrictions.like(“name”,”F%”))

.createCriteria(“kittens”)

.add(Restriction.like(“name”,”F%”)).list();

The second createCriteria() returns a new instance of Criteria that refers to the elements of the Kittens collection.

There is also an alternate from that is useful in certain circumstances.

List cats = sess.createCriteria(Cat.class)

.createAlias(“kittens”,”kt”)

.createAlias(“mate”,”mt”)

.add(Restrictions.eqProperty(“kt.name”,”mt.name”)).list();

 

Conjunction and disjunction:

Conjunction:

Criteria crit = sess.creteCriteria(Employee.class);

Criterion name = Restrictions.like(“lastName”,”Ca%”);

Criterion salary = Restrictions.gt(“salary”,30000.0);

Criterion state = Restrictions.in(“address.state”, new String[]{“MA”,”NC”});

Conjunction cj = Restrictions.conjuction();

cj.add(name);

cj.add(salary);

cj.add(state);

crit.add(cj);

List<Employee> emps = crit.list();

Here the result should satisfy all the three restrictions where as in the case of Disjunction it should satisfy at least one.

Disjunction:

Criteria crit = sess.creteCriteria(Employee.class);

Criterion name = Restrictions.like(“lastName”,”Ca%”);

Criterion salary = Restrictions.gt(“salary”,30000.0);

Criterion state = Restrictions.in(“address.state”, new String[]{“MA”,”NC”});

Disjunction dj = Restrictions.disjunction();

dj.add(name);

dj.add(salary);

dj.add(state);

crit.add(dj);

List<Employee> emps = crit.list();

 

 

 

 

Restrictions:

Important methods of the Restriction class are:

Method Description
Restriction.allEq This is used to apply an “equals” constrain to each property in the set of a Map
Restriction.between This is used to apply “between” constraint to the named property.
Restriction.eq This is used to apply “equal” constraint to the named property.
Restriction.ge This is used to apply “grater than or equal” constraint to the named property.
Restriction.gt This is used to apply “grater than” constraint to the named property.
Restriction.idEq This is used to apply “equal” constraint to the identifier property.
Restriction.ilike This  is case insensitive “like”, similar to Postgres ilike operator
Restriction.in This is used to apply “in” constraint to the named property.
Restriction.isNotNull This is used to apply “isNotNull’  to the named property.
Restriction.isNull This is used to apply “isNull” to the named property.
Restriction.le This is used to apply “less than or equal” to the named property.
Restriction.like This is used to apply “like” constraint to the named property.
Restriction.lt This is used to apply “less than” constraint to the named property.
Restriction.ltProperty This is used to apply “less than” constraint to two properties
Restriction.ne This is used to apply  “not equal” constraint to the named property.
Restriction.neProperty This is used to apply “not equal” constraint to the named property.
Restriction.not This returns negation of an expression.
Restriction.or This returns the disjunction of the two expressions.
   

Adding and Using Restrictions:

  1. 1.     Here is an example code that shows how to use Restrictions.like method and restrict the maximum rows returned by query by setting the Criteria.setMaxResults() value to 5.

Criteria crit = session.createCriteria(Insurance.class);
      crit.add(Restrictions.like("insuranceName""%a%"));      //Like condition
      crit.setMaxResults(5);

  1. 2.     Here is the code of the class using “between” with the Integer class

Syntax: between("property_name",min_int,max_int).

Criteria crit =session.createCriteria(Insurance.class);
      crit.add(Expression.between("investementAmount"new Integer(1000),
       new Integer(2500)));         //Between condition
      crit.setMaxResults(5);          //Restricts the max rows to 5

  1. 3.     Here is the code of the class using “between” with the Date class :

Syntax: between("property_name",startDate,endDate)

 

Criteria crit =session.createCriteria(Insurance.class);
DateFormat format =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate =(Date)format.parse("2005-01-01 00:00:00");
Date endDate = (Date)format.parse("2005-03-03 00:00:00");
crit.add(Expression.between("investementDate"new Date(startDate.getTime()),new Date(endDate.getTime()))); //Between date condition
crit.setMaxResults(5);                                        //Restricts the max rows to 5

 

  1. Here is the code of the class using “eq” Expression :

Syntax: eq("property_name",Object val)

 

Criteria crit =sess.createCriteria(Insurance.class);
DateFormat format = new SimpleDateFormat("yyyy-MM-d hh:mm:ss");
Date date = (Date)format.parse("2005-01-01 00:00:00");
crit.add(Expression.eq("investementDate",date));

 1.5.     Here is the code of the class using “lt” Expression :

 

Syntax: lt("property_name",Object val)

Criteria crit = 
sess.createCriteria(Insurance.class);
 crit.add(Expression.lt("investementAmount",new Integer(900)));

 

  1. 6.     Here is the code of the class using “le” Expression :

Criteria crit =sess.createCriteria(Insurance.class);
crit.add(Expression.le("investementAmount",new Integer(900)));

 

  1. Here is the code of the class using “gt” Expression :

 

Criteria crit =sess.createCriteria(Insurance.class);
crit.add(Expression.gt("lngInsuranceId",new Long(3)));

  1. 8.     Here is the code of the class using “ge” Expression :

 Criteria crit = 
sess.createCriteria(Insurance.class);
        crit.add(Expression.ge
("lngInsuranceId",new Long(3)));

 

  1. 9.     Here is the code of the class using “and” Expression :

 

Expression and(Criterion LHS, Criterion RHS): This method returns the conjunctions of two expressions. Both conditions are ‘true’ then it xecutes the query otherwise not. In this tutorial, “and” is used :

Expression.and(Expression.gt(“lngInsuranceId”, new Long(3), Expression.lt(“IngInsuranceId”, new Long(6))).

Criteria crit =sess.createCriteria(Insurance.class);

crit.add(Expression.and

(Expression.gt("lngInsuranceId",new Long(3)),
 Expression.lt("lngInsuranceId",new Long(6))));

 

  1. Here is the code of the class using “or” Expression :

 

Criteria crit = sess.
createCriteria(Insurance.class);
      crit.add(Expression.or
(Expression.eq("lngInsuranceId",new Long(3)),
 Expression.eq("lngInsuranceId",new Long(6))));

 Projections

Projections: The package Criteria is used as a framework by the applications just to build the new kinds of projection. may be used by applications as a framework for building new kinds of Projection. In general Projection means to retrieve while in case of SQL Projection means “Select” clause. Most of the applications uses the built-in projection types by means of the static factory methods of this class.

  1. Projecting columns

Criteria crit = sess.createCriteria(Product.class);
             ProjectionList proList = Projections.projectionList();
            proList.add(Projections.property("name"));
            proList.add(Projections.property("price"));
             crit.setProjection(proList);

List list = crit.list();

while(it.hasNext()){
             Object[] row = (Object[])it.next();
             for(int i = 0; i < row.length;i++){
            System.out.print(row[i]);
            System.out.println();          }        }

  1. Row count projection

 

Criteria crit = sess.createCriteria(Insurance.class);
             crit.setProjection(Projections.rowCount());
            List result = crit.list();
            System.out.println("No. of rows: "+result);

  1. Summing a column

 

 Criteria crit = sess.createCriteria(Insurance.class);
              ProjectionList proList = Projections.projectionList();
              proList.add(Projections.sum("investementAmount"));
            crit.setProjection(proList);
             List sumResult = crit.list();
             System.out.println("Total Invested Amount: " + sumResult);

  1. Order by projection

List orders = session.createCriteria(Order.class)
.setProjection( Projections.projectionList()
.add( Projections.count(“id”) )
.add( Projections.groupProperty(“id”) )
).list();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Eclipse have been my favorite Java IDE since I started coding in Java. Shortcuts makes life very easy when you are working with any IDE. Eclipse also comes with lot of shortcuts that makes like of a developer easy.

Following are few shortcuts of my choice.

  1. Ctrl + Shift + O : Organize imports
  2. Ctrl + / : Line Comment
  3. Ctrl + Shift + T : Open Type
  4. Ctrl + O : Open declarations
  5. Ctrl + E : Open Editor
  6. Ctrl + Shift + F4 : Close all Opened Editors
  7. Alt + Shift + R : Rename
  8. Alt + Shift + L : Extract to Local Variable
  9. Alt + Shift + M : Extract to Method
  10. F3 : Open Declaration
  11. Alt + Shift + X : Run As…
  12. Alt + Shift + D : Debug As…
  13. Alt + Shift + W : show the class in the package view.
  14. Ctrl + T : Type hierarchy
  15. Ctrl+Q : Last edit
  16. Alt + Left or Alt + Right : Navigate Left and Right
  17. Ctrl + 1 : Quick Fix
  18. Ctrl + Space : Content Assist
  19. Alt + Shift + F : Format code
  20. Alt + Shift + S + R : Generate getter and setter methods

Hello world!

Posted: March 12, 2012 in Uncategorized

Welcome to WordPress.com. After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.