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=true由many方来进行关联关系的维护
<manytomany>中只设置其中一方inverse=false或双方都不设置
Cascade通常情况下都不会使用特别是删除一定要慎重
操作建议
一般对manytoone和manytomany不设置级联这要看业务逻辑的需要对onetoone和onetomany设置级联
manytomany关联关系中一端设置inverse=false另一端设置为inverse=true在onetomany关联关系中设置inverse=true由多端来维护关系表