Hibernate对视图的操作
Hibernate对视图进行操作时和对普通的表有些不同,下面就是一个Hibernate操作视图的例子:
视图:
SELECTa.SPID,a.SPKey,b.serviceID,b.serviceName,c.serviceItemID,c.itemName
FROMdbo.tbSPInfoa
INNERJOINdbo.tbServicebONa.SPID=b.SPIDLEFTOUTERJOIN
dbo.tbServiceItemcONb.serviceID=c.serviceID
1.首先根据视图中的字段定义一个bean
importjava.io.Serializable;
publicclassServiceIdimplementsSerializable{
privatestaticfinallongserialVersionUID=-2298938310945830572L;
privateStringspId;
privateStringspKey;
privateStringserviceId;
privateStringserviceName;
privateStringserviceItemId;
privateStringitemName;
publicServiceId()...{
super();
}
publicStringgetItemName()...{
returnitemName;
}
publicvoidsetItemName(StringitemName)...{
this.itemName=itemName;
}
publicStringgetServiceId()...{
returnserviceId;
}
publicvoidsetServiceId(StringserviceId)...{
this.serviceId=serviceId;
}
publicStringgetServiceItemId()...{
returnserviceItemId;
}
publicvoidsetServiceItemId(StringserviceItemId)...{
this.serviceItemId=serviceItemId;
}
publicStringgetServiceName()...{
returnserviceName;
}
publicvoidsetServiceName(StringserviceName)...{
this.serviceName=serviceName;
}
publicStringgetSpId()...{
returnspId;
}
publicvoidsetSpId(StringspId)...{
this.spId=spId;
}
publicStringgetSpKey()...{
returnspKey;
}
publicvoidsetSpKey(StringspKey)...{
this.spKey=spKey;
}
}
...2.定义一个bean,用组合方式将ServiceId包含进去
importjava.io.Serializable;
publicclassServiceViewimplementsSerializable{
privatestaticfinallongserialVersionUID=-2909733442648785569L;
privateServiceIdid;
publicServiceView()...{
super();
}
publicServiceIdgetId()...{
returnid;
}
publicvoidsetId(ServiceIdid)...{
this.id=id;
}
}
...3.映射文件
<!DOCTYPEhibernate-mappingPUBLIC
"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="com.txsec.lc.is.bean.ServiceView"table="vwSPService">
<composite-idname="id"class="com.txsec.lc.is.bean.ServiceId">
<key-propertyname="spId"type="string">
<columnname="SPID"/>
</key-property>
<key-propertyname="spKey"type="string">
<columnname="SPKey"/>
</key-property>
<key-propertyname="serviceId"type="string">
<columnname="serviceID"/>
</key-property>
<key-propertyname="serviceName"type="string">
<columnname="serviceName"/>
</key-property>
<key-propertyname="serviceItemId"type="string">
<columnname="serviceItemID"/>
</key-property>
<key-propertyname="itemName"type="string">
<columnname="itemName"/>
</key-property>
</composite-id>
</class>
</hibernate-mapping>ok,用HQL进行查询时,就可以这样:
session.createQuery("fromServiceViewsvwheresv.id.serviceId='100001'").list();
查询返回的是ServiceView对象或集合,要得到视图中字段的值,只需要调用ServiceView对象的getId()方法即可获得ServiceId对象,通过ServiceId对象的getXXX()方法,就可以访问到视图中的字段了。