【问题标题】:Inner join on two tables which are not mapped using HQL未使用 HQL 映射的两个表的内部联接
【发布时间】:2018-11-04 09:54:57
【问题描述】:

我的表 A 和表 b 没有关系。但是表A、表B与实体映射,实体之间没有关系。 假设表映射如下。

@Entity
@Table(name = "tableA")
public class TableA

@Entity
@Table(name = "tableB")
public class TableB

表 A

伊达, 参考编号, 架构, 输入

表 B

idb, 户口号码, 图式, 输入

我需要从 tableB 中获取具有相同“schema”和“type”的给定“ref_no”的“accountno”。我可以在实现 CrudRepository 的存储库类中使用以下本机 SQL 查询获取“accountno”。

@Query(value = "SELECT b.accountno FROM DB.tableA as a INNER JOIN DB.tableB as b ON b.sechema = a.sechema AND b.type = a.type WHERE a.ref_no= ?1", nativeQuery = true)
Integer findByRefNo(String refNo);

有人可以帮我解决这个问题吗,因为使用本机查询,如果数据库名称不同,我需要更改。

我在下面尝试过,但它给了我错误。

@Query(value = select b.accountno from TableA a join TableB b where b.sechema = a.sechema and b.type = a.type and (:refNo is null or a.refNo = :refNo)")
Integer findByRefNo(@Param("refNo") String refNo);

【问题讨论】:

  • 如果您尝试的某些操作导致异常,请在问题中包含异常(完整的调用堆栈)。它通常有助于找到合适的答案,如果其他人遇到类似问题,也可以帮助他们找到问题。

标签: mysql spring-boot spring-data-jpa hibernate-mapping


【解决方案1】:

如果您使用的是 Hibernate 5.1+,则查询在 HQL 中几乎相同:

@Query("select b.accountno from TableA a join TableB b on b.sechema = a.sechema and b.type = a.type where a.ref_no= ?1")
Integer findByRefNo(String refNo);

更多信息:12

【讨论】:

  • 感谢 Cerp0。我会尝试并告诉你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2017-01-15
  • 2012-08-20
  • 1970-01-01
  • 2022-10-02
  • 1970-01-01
相关资源
最近更新 更多