熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Hibernate的HQL多表聯合查詢使用left join方式

2022-06-13   來源: Java開源技術 

  Hibernate不支持left join帶on的條件查詢

  解決辦法使用原生SQL或者使用HQL方式需要修改hbm文件(如果項目中大部分不適用級聯配置情況下)

  需求是查詢網絡信息網絡信息中關聯了分區網絡IP(個網絡N個網絡IP)網橋信息

  HQL:

  public void queryVnets(Page page) {

  StringBuffer hql = new StringBuffer()

  hqlappend(select new Map(vnid as id vnvnName as vnName bname as vnType

  hqlappend(vnvnIptype as vnIptype vnvnIp as vnIpvnvnNat as vnNat vnvnFlag as vnFlag

  hqlappend(vnvnetFlag as vnetFlag (case when sum(vmvnstate)= then else end) as vnState

  hqlappend(vnuseType as useType vncreateTime as createTime

  hql append(zoneoneName as oneName zoneoneHypervisor as oneHypervisor zoneoneSeq as oneSeq)

  hqlappend(from VnetTable vn ZoneTable zone BridgeTable b

  hqlappend(left join fetch vnVnTables vmvn where zoneid = vnzoneId and vnvnType = bid

  … …

  hqlappend( group by vnid

  if (vnState != null && !equals(vnState)) {

  if (equals(vnState)) {

  hqlappend( having sum(vmvnstate)=

  } else if (equals(vnState)) {

  hqlappend( having sum(vmvnstate)!=

  }

  }

  }

  hbm配置文件

  <?xml version= encoding=utf?>

  <!DOCTYPE hibernatemapping PUBLIC //Hibernate/Hibernate Mapping DTD //EN

  hiber/hibernatemappingdtd>

  <!

  Mapping file autogenerated by MyEclipse Persistence Tools

  >

  <hibernatemapping>

  <class name=combasemappingVnetTable table=vnet_table >

  <id name=id type=javalangString>

  <column name=ID length= />

  <generator class=uuidhex />

  </id>

  <property name=vnId type=javalangLong>

  <column name=VN_ID>

  <comment>創建虛擬網絡時得到的ID</comment>

  </column>

  </property>

  …

  <property name=zoneId type=javalangString>

  <column name=ZONE_ID length=>

  <comment>分區ID</comment>

  </column>

  </property>

  <property name=vlanId type=javalangInteger>

  <column name=VLAN_ID>

  <comment>VLAN_ID</comment>

  </column>

  </property>

  <set name=vnTables lazy=false orderby=id asc inverse=false fetch=join cascade=all>

  <key column=VN_NID/>

  <onetomany class=combasemappingVnTable/>

  </set>

  </class>

  </hibernatemapping>

  理解inverse和cascade

  總結

  <onetomany>中建議inverse=truemany方來進行關聯關系的維護

  <manytomany>中只設置其中一方inverse=false或雙方都不設置

  Cascade通常情況下都不會使用特別是刪除一定要慎重

  操作建議

  一般對manytoone和manytomany不設置級聯這要看業務邏輯的需要對onetoone和onetomany設置級聯

  manytomany關聯關系中一端設置inverse=false另一端設置為inverse=true在onetomany關聯關系中設置inverse=true由多端來維護關系表


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28554.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.