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

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

I\'m developing webapp using Spring & Hibernate.

Table 1: BaseTable

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


        
相关标签:
2条回答
  • 2021-01-12 17:54

    You need to use native query for this purpose

    String sql = "SELECT A.* FROM Table2 As a INNER JOIN Table1 As b "
               + " ON (a.Serial = b.Serial1 or a.Serial = b.Serial2);";
    SQLQuery query = session.createSQLQuery(sql);
    query.addEntity(Table2.class);
    List<Table2> tableContent  = query.list();
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题