Hibernate - Is there a way to join 2 columns against 1?

前端 未结 2 673
清酒与你
清酒与你 2021-01-12 17:41

I\'m developing webapp using Spring & Hibernate.

Table 1: BaseTable

+------------+--------------+------+-----+---------+----------------+
| Fiel         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 17:57

    Solution 1

    Create a database view on the Table1 which exposes foreign key referencing Table2. Project the foreign key from your posted query which you will use for the view anyway. Then map your entity to the view.

    Solution 2

    Use join formula:

    For example, in the entity mapped to Table1 define the many-to-one association with the entity mapped to Table2 (seems to be your use case):

    @ManyToOne
    @JoinColumnsOrFormulas({
          @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT t2.serial FROM Table2 t2 WHERE serial1 = t2.serial OR serial2 = t2.serial)", referencedColumnName="serial"))
        })
    private Entity2 entity2;
    

    However, join formulas seem to be very fragile in Hibernate for the time being (I managed to make this work only for many-to-one association and I had to make Entity2 implement Serializable; otherwise it did not work and threw some strange NullPointer- and ClassCastExceptions).

提交回复
热议问题