Monday, March 15, 2010

Hibernate Native SQL

Hiberante HQL/Criteria doesn't support the query for Map collection with dereferenced key object. AddEntity() method will convert the result into domain object, otherwise, it would be an object array.


String sqlStr = "select t.* from ce_template t, ce_apProfileTemplate_wlanServiceTemplate aw "
+ "where t.id=aw.apProfileTemplateId and t.templateType='APPROFILE' and t.oldId=0 "
+ "and aw.wlanServiceTemplateId=:id";
Query query = getSession().createSQLQuery(sqlStr)
.addEntity("t", Template.class)
.setInteger("id", t.getId());

Sunday, March 7, 2010

烟霞闲骨格,泉石野生涯。

探春秋爽斋内对联

Saturday, March 6, 2010

Formula in Map



<key column="ITEM_ID"/>
<map-key type="string" column="IMAGENAME"/>

<property name="filename" column="FILENAME" not-null="true"/>
<property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>



This has the drawback that the embedded component class (Image) doesn't have the property imageName which is the map key. It may be undesirable.


<key column="ITEM_ID"/>
<map-key type="string" column="IMAGENAME"/>

<property name="name" type="string" formula="IMAGENAME"/>
<property name="filename" column="FILENAME" not-null="true"/>
<property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>



In Hibernate 3.x, formula comes as a rescue here.

[Reference] Hibernate: how to map a collection of embedded components keyed by one of the component's properties?

Tuesday, February 9, 2010

n+1 select & fetch strategy

The n+1 select is for return *LIST* of objects, and the object contains collection. Then we can use 'subselect' fetch strategy to reduce the number of queries. For example, Template (1-->*) DeployedController, with default fetch strategy 'select', to return a list of template it requires 1 + n selects.


select * from template;
select * from deployedController where templateId=?
select * from deployedController where templateId=?
...

With 'subselect', it becomes only 2 queries -

select * from template;
select * from deployedController where templateId in (select id from template)

This is for lazy loading, the 2nd query is run when the 1st time the deployedController collections is accessed. For eager loading, change fetch strategy to 'join', then only one query (left outer join) is used but the resultset contains duplicate or null values.

The subselect option is currently only available for collection, not for *-->1 assocation.

Eager loading:
1. lazy="false", stands for fetch="select", follow by an immediate second select
2. fetch="join"
Lazy Loading:
1. fetch="subselect"
2. batch-size="N"