如何使用JPA和Hibernate加入两个不相关的实体 [英] How to join two unrelated entities using JPA and Hibernate

查看:98
本文介绍了如何使用JPA和Hibernate加入两个不相关的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张表 - 一张包含地址,另一张包含照片。他们之间唯一的共同领域是PersonID。这些映射到两个POJO类地址和照片。我能够通过创建标准并在字段中添加限制来获取这些表中的详细信息。我们应该如何在两个表上编写连接。是否有可能将结果作为两个对象 - 地址和照片。



我想进行左连接,这样我就可以获得没有照片的人的记录。
我已经读过,这是可能的只能使用hql,但是这可以使用标准吗?

解决方案

您可以轻松编写HQL查询,该查询将使用Theta Join将结果作为两个对象返回(如Adrian指出的那样)。这里是一个例子:

 字符串queryText =选择地址,照片来自地址,照片照片其中address.personID =照片。 PERSONID; 
List< Object []> 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]);





$ b

正如你所看到的,查询返回Object []数组的列表,行。这个数组的第一个元素将包含一个obejct和第二个元素 - 另一个元素。



编辑:



在左连接的情况下,我认为您需要使用原生SQL查询(而不是HQL查询)。这里你如何做到这一点:

  String queryText =select address。*,photo。* from ADDRESS address 
(address.person_id = photo.person_id)上加入PHOTO照片;

List< Object []> rows = sess.createSQLQuery(queryText)
.addEntity(address,Address.class)
.addEntity(photo,Photo.class)
.list();

这适用于您的情况。


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 Address and Photo. I was able to fetch details in these tables by creating criteria and adding restrictions on the fields . How should we write a join on the two tables. Is it possible to get the result as two objects -Address and Photo.

I want to do a left join so that i can get records of persons without photos as well. I have read that this is possible only using hql but Can this be done using criterias as well?

解决方案

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<Object[]> 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<Object[]> rows = sess.createSQLQuery(queryText)
                          .addEntity("address", Address.class)
                          .addEntity("photo", Photo.class)
                          .list();

This should work for your case.

这篇关于如何使用JPA和Hibernate加入两个不相关的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆