简体   繁体   English

Hibernate 带有 POJO 构造函数的 JoinColumn(没有实体)

[英]Hibernate JoinColumn with a POJO constructor (without an Entity)

I have a POJO that looks something like this我有一个看起来像这样的 POJO

@AllArgsConstructor
public class POJO {
  @Getter
  @Setter
  private String name;

  @Getter
  @Setter
  private int age;
}

I use this POJO to set values from a hql query as in我使用这个 POJO 从 hql 查询中设置值,如

session.createQuery("Select new fullyQualifiedName.POJO(emp.name, emp.age) From Employee emp where emp.id = 1");

Recently, I've been asked to make a request to add a List property to the POJO.最近,有人要求我向 POJO 添加一个 List 属性。 As in,如中,

@AllArgsConstructor
public class POJO {
  @Getter
  @Setter
  private String name;

  @Getter
  @Setter
  private int age;

  @Getter
  @Setter
  private List<Hobby> hobbies;
}

However, at this point, I do not know how to join Hobby table, get values as a list and pass to the constructor.但是,此时,我不知道如何加入爱好表,以列表的形式获取值并传递给构造函数。

What are the possible ways to accomplish this?有哪些可能的方法来实现这一目标?

I don't think you can achieve what you want with the new keyword anymore.我不认为你可以用new关键字来实现你想要的。 Maybe others might be more helpful on this construct but I have not seen any example providing a collection with the new keyword, yet.也许其他人可能对这个结构更有帮助,但我还没有看到任何提供带有new关键字的集合的示例。 I think this construct has some limitations.我认为这个结构有一些局限性。

As for the solution I propose:至于我提出的解决方案:

  1. Change your query to Select emp, h From Employee emp left join Hobby h where emp.id = 1 .将您的查询更改为Select emp, h From Employee emp left join Hobby h where emp.id = 1 You can also use inner join depending on your use case.您还可以根据您的用例使用内部联接。

  2. Set a custom ResultTransformer to your query object.为您的查询 object 设置自定义 ResultTransformer。 Something like:就像是:


    query.setResultTransformer(
        new ResultTransformer() {
            @Override
            public Object transformTuple(Object[] tuple, String[] aliases) {            
                return tuple;
            }
            @Override
            public List transformList(List collection) {
               //Each member of collection is a Object[], we are working at row level 
               //You should process the collection, eliminate duplicates etc and return a 
               //List containing a single POJO object
            }
        }
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM