JoinColumn与多列串联引用。从*引用*的外键的列号错误

时间:2018-12-12 22:43:53

标签: java sql oracle hibernate-5.x

  

抱歉,标题很尴尬,没有简单的方法可以概括我的问题。

我有2个相关实体:

  

真实数据已被修改以保护敏感IP,但是问题是相同的。因此,请不要被不完整的领域所分散。

# Permission
+----------------+--------------+
|    Column      |     type     |
+----------------+--------------+
| perm_id        | Number(20,0) |
| item_id1_id2   | VARCHAR2(8)  |
| date_code      | VARCHAR2(6)  |
+----------------+--------------+

# Item
+-----------------+-------------+
|    Column       |    type     |
+-----------------+-------------+
| id1             | VARCHAR2(4) |
| id2             | VARCHAR2(4) |
| date_code       | VARCHAR2(6) |
| some_data_field | VARCHAR(20) |
+-----------------+-------------+

Permission @ManyToOne 具有Item关系。 Permission 通过下面的SQL逻辑链接到 Item

SELECT p.*, i.*
FROM Permission p
JOIN (
    SELECT
        id1 || id2 as joined_ids,  -- the p.item_id1_id2 is 2 CONCATed columns to Item.id1 and Item.id2
        effective_date_code, -- this column specifies WHEN this data is effective by, i.e. all date codes for permissions between this date and not including the next greatest date should link to this record.
        some_data_field, -- and arbitrary data point that gives this object its usefulness.
        rank() over (partition by id1, id2 order by effective_date_code DESC) max_date_code -- this essentially gives us the 
    FROM Item
--    where   effective_date_code <= p.date_code
    ORDER BY max_date_code
) i
ON i.max_date_code = 1
and p.item_id1_id2 = i.joined_ids
;

如您所见,联接相当复杂,到目前为止,我尝试使用Hibernate的API的尝试都是徒劳的。请注意,这些高度依赖于无法进行架构更改的旧表,因此这是不可能的。

我尝试使用@JoinColumnsOrFormulas注释及其相关内容:

public class Permission {
    // ...

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumnsOrFormulas(value = {
            @JoinColumnOrFormula(formula = @JoinFormula(value = "item_id1_id2", referencedColumnName = "id1 || id2")),
            @JoinColumnOrFormula(column = @JoinColumn(name = "date_code", referencedColumnName = "effective_date_code")) // This isn't the final thing, but just for testing purposes I'm linking like this.
    })
    public Subject subject;
}

但我收到投诉:

java.lang.RuntimeException: org.hibernate.AnnotationException: A Foreign key 
\ refering com.example.Item from com.example.Permission has the wrong number 
\ of column. should be 3...

我是否期望ORM过多,应该将查询分为更易于管理和可行的部分,还是可以使用休眠模式?

0 个答案:

没有答案