How to join two unrelated entities using JPA and Hibernate

前端 未结 6 2168
天命终不由人
天命终不由人 2020-12-08 08:26

I have two tables - one containing Address and another containing Photographs. The only common field between them is the PersonID. These were mapped to two POJO Classes Add

6条回答
  •  误落风尘
    2020-12-08 09:15

    You can easily write HQL query that will return result as two objects using Theta Join (as Adrian noted). Here is an example:

    String queryText = "select address, photo from Address address, Photo photo " 
                     + " where address.personID=photo.personId";
    List rows = session.createQuery(queryText).list();
    
    for (Object[] row: rows) {
        System.out.println(" ------- ");
        System.out.println("Address object: " + row[0]);
        System.out.println("Photo object: " + row[1]);
    }
    

    As you can see query returns list of Object[] arrays that represents each fetched row. First element of this array will contain one obejct and second element - another.

    EDIT:

    In case of left join I think you need to use native SQL query (not HQL query). Here how you can do this:

    String queryText = "select address.*, photo.* from ADDRESS address 
                        left join PHOTO photo on (address.person_id=photo.person_id)";
    
    List rows = sess.createSQLQuery(queryText)
                              .addEntity("address", Address.class)
                              .addEntity("photo", Photo.class)
                              .list();
    

    This should work for your case.

提交回复
热议问题