Google

Oct 8, 2013

Hibernate Query Language (HQL) example



Step 1: The ER diagram showing the relationships among the tables. The column names and types are omitted to keep it simple.



Step 2: The basic table details.


The UserApp table uses "UserName" and "AppCd" as the primary key. It links to the User table using the "UserName". "UserName" is the primary key in the User table.



The UserApp table links to the App table using the "AppCd".


"AppCd" is the primary key in the App table.

-->
Step 3: Now the sample  HQL.


    public List getAppGroupActions(String userName)
    {
        
        String hql = "Select new com.myapp.model.security.UserAppId(user.userName, app.appCd)"
                + " from UserApp as usrapp, App app, User user "
                + " where  user.userName = usrapp.id.userName"
                + " and usrapp.id.appCd  = app.appCd "
                + " and usrapp.status='A' 
                + " and app.status='A' AND app.disabled = 'N' "
                + " and user.status = 'A' and user.disabled = 'N' "
                + " and usrapp.id.userName = :userName ";
        
        Query query = em
                .createQuery(hql);
        query.setParameter("userName", userName);
        
        @SuppressWarnings("unchecked")
        List resultList = query.getResultList();
        
        return resultList;
 }

Things to observe are:

  • A list new object of type new com.myapp.model.security.UserAppId is returned. You need to have this class defined with the right constructor to take userName and appCd
  • The UserApp,  App,  and User are hibernate entities and NOT table names.
  • usrapp.id.userName, user.status, etc are entity properties and NOT table column names.
You can refer here as to how the entities are defined and mapped.

So, this is an Object Oriented query language. 

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home