Hibernate计算从表记录数

  

有一个主表,其中一个字段是从表对应的记录数,为了避免在查询时把从表的记录全部查询出来,不使用one-to-many关联,有一种方法就是通过formula来实现。

从表Mapping文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.huatek.hbwebsite.common.entity">
  <class name="HousePic" table="house_picture">
    <id name="erpId" type="java.lang.String" column="erp_id"></id>
    <property name="houseId" column="house_id" type="java.lang.String"/>
    <property name="houseType" column="house_type" type="java.lang.Integer"/>
    <property name="picType" column="picture_type" type="java.lang.Integer"/>
    <property name="picComment" column="picture_comment" type="java.lang.String" length="1000"/>
    <property name="picUrl" column="picture_uri" type="java.lang.String" length="500"/>
    其他省略.
  </class>
</hibernate-mapping>

 

 

主表Mapping文件:

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.huatek.hbwebsite.common.entity">
  <class name="com.huatek.hbwebsite.common.entity.Community" table="house_community">
    <id name="erpId" type="java.lang.String" column="erp_id" length="40"></id>
    <property name="pictureCount" type="java.lang.Integer" length="11"
        formula="(select count(*) from house_picture pic where pic.house_id=erp_id and pic.house_type=3)"></property>
  </class>
</hibernate-mapping>

 

 

 

 

你可能感兴趣的:(Hibernate)