java - HQL Hibernate 不相关实体,但 id 相同

标签 java hibernate mapping hql cross-join

我有两个类

  • 验证
  • 契约(Contract)

具有以下结构:

  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映射中也没有关联,但是在保存Contract时,它必须具有相同的verificationId y contractId 字段(业务规则),但某些情况下也会给出未经验证的契约(Contract)。

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 查询?

规则:不应是映射实体。

最佳答案

您可以按如下方式映射两个表之间的联接关系:

@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。

关于java - HQL Hibernate 不相关实体,但 id 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996987/

相关文章:

java - 这种情况会不会是mongodb服务器的bug呢?

java - hibernate : Help in resolving exception org. hibernate.HibernateException: 缺少表

java - Tomcat jdbc 连接池 - Pool-Cleaner Memory Leak

java - Hibernate 从数据库中获取列表

java - Hibernate 延迟加载应用程序设计

mapping - 没有注释的 JACKSON 映射 XML 配置

c - GCC 以相反的顺序编译 EEPROM 地址

c# - 简单的 FluentNHibernate 父/子映射

java - 在 Java Swing 中,当另一个 JPanel 中的 ComboBox 发生更改时,会触发 JPanel 中的更新

java - 如何使 JFrame 中出现新图像?