Hibernate20Adapter

This ValueListAdapter returns a ValueList of pojos delegating the data access to Hibernate.

Properties

NameRequiredDefaultDescription
adapterTypeN0 A bitwise or of the following:
  • 1 If you want the sorting done in the JVM.
  • 2 If you want paging done in the JVM.
  • 4 If you want filtering done in the JVM.(not implemented yet)
  • 8 If you want focusing done in the JVM. (not implemented yet)
sessionFactoryYN/AAn instance of Hibernate SessionFactory.
hsqlDEPRECATEDInstead, please use hql
hqlYOne of the two are required. The Hibernate query is defined in the Spring config file. (image)
namedQuery The name of the Hibernate query that is defined in your mapping file. (image)
We recommend to not use this, while you want to use features such are focusing and sorting.
defaultNumberPerPageNInteger.MAX_VALUE The number if items per page. This can be overriden by a value in the ValueListInfo.
defaultSortColumnNN/A The column to sort the results upon. This can be overridden by a value in the ValueListInfo.
defaultSortDirectionNN/A The direction (asc or desc) to sort the results in. This can be overridden by a value in the ValueListInfo.
allowCreateNtrue If a new Session should be created if no thread-bound found.
maxRowsForFocusNLong.MAX_VALUE; The max rows in ResulSet to do focus search.
defaultFocusPropertyObjectAliasN"" The name of object use to get focus property in hibernate sql syntax SELECT defaultFocusPropertyObjectAlias.focusProperty FROM ...
removeEmptyStringsNfalseEnable or Disable String length checking of given filters values. If filter value is null or empty is removed from query.
validatorNnullValidator add possibility to do any postprocessing of selected records.
focusOptimalizationNtrueEnable or Disable optimalization of statement for focus query.
statementBuilderNImplicit object with default String setter for all keys.Supports Long, Timestamps and other hibernate types to set to "preparedStatement" of hibernate query. It is used with conjuction of filters.

Sample config file.

You will notice the hql in the <hql> tag is not valid hql. The line: /~sortColumn: ORDER BY [sortColumn] [sortDirection]~/ contains chars '/', '~', '[' and ']'; all invalid chars in thier context. Let me explain what is happening here.

Filters

You can limit records (objects) shown in a valuelist to those matching certain criteria thanks to something that is called "filters". The Hibernate20Adapter uses the values in the ValueListInfo.filters to dynamically build the query. The following rules are applied.

  • /~sortColumn: ~/ This is called a filter. The contents between the /~ and the ~/ are included only if the ValueListInfo.filters map contains the key 'sortColumn'.
  • [sortColumn] This is called a constant. The contents between the [ and the ] are replaced with the value in the ValueListInfo.filters map. For example:

    'ORDER BY [sortColumn] DESC' = 'ORDER BY my_sorted_column DESC'

  • {name} This is called a bind varable. The contents between the { and the } are replaced with a ?, then the value in the ValueListInfo.filters map is set on the PreparedStatement. For example:

    'WHERE user.name = {name}' = 'WHERE user.name = :name'

    NOTE: The Hibernate20Adapter set your bind varable as string to PreparedStatement as default. (It is something like this:Query.setString("name",(String) valueListInfo.getFilters().get("name"));) Of course Hibernate20Adapter can set also other types such as Timestamps. To do that, you need to declare map with a cuple of the name of your key and a type of your key. The manager for this map is called StatementBuilder.

<property name="statementBuilder">
  <bean class="net.mlw.vlh.adapter.hibernate.util.StatementBuilder">
    <property name="setters">
       <map>
         <entry key="name">
           <bean class="net.mlw.vlh.adapter.hibernate.util.setter.StringSetter" />
         </entry>
		 <entry key="myLongId">
           <bean class="net.mlw.vlh.adapter.hibernate.util.setter.LongSetter" />
         </entry>
       </map>
     </property>
  </bean>
</property>

The Bind varable:
  • {name} will be set adapter as String.
  • {myLongId} will be set adapter as Long. (You can imagine like this:Query.setLong("myLongId",(Long) valueListInfo.getFilters().get("myLongId"));)

NOTE: StatemntBuilder is used analogical in jdbc based adapters. See war example adapters config file.

Focusing

If you like to use the focus feature, you must tell Hibernate20Adapter what to focus. You can do it directly to set focusValue, focusProperty. And you have to also enable it every time you want to focus. Focus will be automatically turned off, when you will press next page button in your html page for example.


ValueListInfo info = valueListHelper.getValueListInfo(request, "MyTable"); 

info.setFocusValue(player.getId());  //We assume that you have object Player with the property 'id'.
info.setFocusProperty("id"); 
info.setDoFocus(true); //do focus when retrieving!

valueListHelper.backupInfoFor(request, info, "MyTable"); ... 

In this example is disabled sorting for the first column. You can enabled it with sortable="desc".

The next tag that is usefull is focusStatus. It represents what happened during the focus searching. This tag create a table only if the focus is enabled. The focus will be enabled if you set non null value to the focus property (in service or in jsp). For more detail see taglibdoc for focus status tag.

Focusing for other adpaters or in JVM is work in progress. :))

Dependencies

See hibernate site.

Validator

Sometimes is your solution too complex to retrieve needed objects from a persistance tier using hibernate. In this case you appreciate usage of so called ObjectValidators. Validators help you with filtering of reselt set in JVM and still support paging and other features of this Hibernate20Adapter.

Before use of validators, you need to:

  1. Implement your interface ObjectValidator
    public class PlayersObjectValidator implements ObjectValidator
    {
        /**
         * Logger for this class
         */
        private static final Log LOGGER = LogFactory
                .getLog(PlayersObjectValidator.class);
    
        /**
         * @see net.mlw.vlh.adapter.util.ObjectValidator#isAcceptable(java.lang.Object)
         */
    	public boolean isAcceptable(Object objectToBeChecked)
        {
            Player p = (Player) objectToBeChecked;        
    
            boolean accepted;
            if ( p.getLastName()!=null && p.getLastName().equalsIgnoreCase("Williams") ){
                LOGGER.info("Accepted player : " + p);
                accepted = true;
            } else{
                LOGGER.debug("Rejected player : " + p);
                accepted = false;
            }
            return accepted;
        }
    	
    	/**
        * @see net.mlw.vlh.adapter.util.ObjectValidator#setValueListInfo(net.mlw.vlh.ValueListInfo)
        */
        public void setValueListInfo(ValueListInfo info)
        {
    		// This method is called by adapter! 
            // In this example is it not used, you can use it as additional way how
            // to pass some additional parameters to method isAcceptable.
        }
    	
    }	
    
  2. Create bean for your for example PlayersObjectValidator and set it to property validator of Hibernate20Adapter.
     
    <bean id="Players1Validator" class="net.mlw.data.PlayersObjectValidator"/>
      ...
    <bean id="valueListHandler" singleton="true" 
            class="net.mlw.vlh.DefaultValueListHandlerImpl">
     <property name="config.adapters">
          <map>
    	    ...
      		<entry key="players1Validator">
              <bean class="net.mlw.vlh.adapter.hibernate.Hibernate20Adapter">
    		
    			<property name="validator"><ref bean="Players1Validator"/></property>  
    			<property name="focusOptimalization"><value>false</value></property>
    		
    			<!-- the rest -->
                <property name="sessionFactory"><ref bean="mySessionFactory"/></property>
                <property name="defaultNumberPerPage"><value>2</value></property>
                <property name="defaultSortColumn"><value>lastName</value></property>
                <property name="defaultSortDirection"><value>asc</value></property>
                <property name="hql">
                  <value>
                    FROM net.mlw.data.Player AS vo
                    /~name: WHERE vo.lastName LIKE {name} ~/
                    /~sortColumn: ORDER BY vo.[sortColumn] [sortDirection]~/
                  </value>
                </property>
                <property name="defaultFocusPropertyObjectAlias"><value>vo</value></property>
                <property name="maxRowsForFocus"><value>160000</value></property>            
    			<property name="removeEmptyStrings"><value>true</value></property>
    		  </bean>
            </entry>
    		
    		...
    	</map>
    </bean>
    
    

  • This solution is recommended in the case when you cannot do a filtering in database tier. Using validators may greatly slow down a performance because it's done in JVM.
  • You should also turn off the query optimalization for focus. Set the property focusOptimalization in Hibernate20Adapter to false.
  • Normally focus select only focus property (for example an ordinary number - id) and not whole object to fast detect, on which page is focused record. Thus if you need to controll only focus property, you can let optimalization turned on.

For more information see war file example (version 0-1-7Beta9 or higher).

Dependencies

See hibernate site.