【问题标题】:HQL Hibernate un-related entities, but same idHQL Hibernate 不相关的实体,但相同的 id
【发布时间】:2015-01-15 19:10:42
【问题描述】:

我有两节课

  • 验证
  • 合同

结构如下:

  public class Verification implements Serializable {
     private Long verificationId;
     private Long salesManCode;
     private Long clientCode;
     ...
  }

  public class Contract implements Serializable {
     private Long contractId;
     private Long salesManCode;
     private Long clientCode;
     ...
  }

这些类有各自的hbm.xml映射,在数据库模型中,表没有关联,在hibernate映射中也没有,但是在保存合同时,它必须具有相同的verificationIdcontractId字段(业务规则),但有些情况下也有不经验证的合同。

verification
 verificationId | salesManCode | clientCode
  1050              1001            2056
  1051              1001            2248
  1054              1002            2856

contract
 contractId | salesManCode |clientCode
  1050         1001          2056         <- this contract have verification
  1051         1001          2248         <- this contract have verification
  1052         1025          2822         <- this contract not have verification
  1053         1254          1547         <- this contract not have verification
  1054         1002          2856         <- this contract have verification

我的问题是当我运行 HQL 查询时:

select con.salesManCode,  ver.salesManCode, con.clientCode, ver.clientCode, con.contracId, ver.verificationId 
from Verification ver, Contract con
where ver.verificationId = con.contractId

但是 Hibernate 使用交叉连接语句进行翻译并合并所有记录。 有什么方法可以在hbm.xml 文件中不相关的类之间执行 HQL 查询?

规则:不应映射实体。

【问题讨论】:

    标签: java hibernate mapping hql cross-join


    【解决方案1】:

    两个表的连接关系可以如下映射:

    @Entity
    public class Verification implements Serializable {
        private Long verificationId;
    
        private Long salesManCode;
        private Long clientCode;
        ...
    }
    
    @Entity
    public class Contract implements Serializable {
        private Long contractId;        
    
        @MapsId
        @OneToOne
        @JoinColumn(name = "contractId", referencedColumnName = "verificationId")
        private Verification verification;
    
        private Long salesManCode;
        private Long clientCode;
    }
    

    您的查询变为:

    select con.salesManCode, ver.salesManCode, con.clientCode, ver.clientCode, con.contracId, ver.verificationId 
    from Contract con
    join con.verification ver
    

    因此,您得到的是 INNER JOIN,而不是 CROSS JOIN。

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 1970-01-01
      • 2011-12-17
      • 2016-02-04
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      相关资源
      最近更新 更多