带有显式自定义类的getNamedQuery [英] getNamedQuery with explicit custom class

查看:143
本文介绍了带有显式自定义类的getNamedQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个Person模型(Java类和数据库表),该模型具有诸如姓名,年龄,性别,身高,体重之类的列/字段.

Say I have a Person model (Java class and Database table) which has columns/fields like name, age, gender, height, weight.

现在有2种可能性

1)我将需要整个列数据..so,我将使用命名查询

1) I would need the entire column data..so i would have the named query as;

@NamedQuery(name ="Person.findAll",query =从Person中选择p 在哪里..."

@NamedQuery(name = "Person.findAll", query = "Select p from Person WHERE ..."

2)我只需要特定的列数据..所以我将使用命名查询作为

2) I need only specific column data..so i would have the named query as;

@NamedQuery(name ="Person.findSpecific",查询=选择p.name, 来自WHERE人的页码..."

@NamedQuery(name = "Person.findSpecific", query = "Select p.name, p.age from Person WHERE ..."

在第一种情况下,如果我以以下方式调用/执行命名查询;

In the first case, if I call/execute the named query as;

Query query = getNamedQuery("Person.findAll");

它自动将响应映射到Person Java类.但是在第二种情况下(特定列),事实并非如此.它将响应显示为带有对象数组的Vector.

it automatically maps the response to the Person Java class. But in the 2nd case (specific columns), it does not. It shows the response as Vector with Object array.

我的问题是,当我使用特定的列查询时,是否有任何明确的方法可以使查询响应映射自动映射到我的自定义类

My question is is there any explicit way of making the query response map automatically to my custom class when I am using the specific column query

我已经尝试过

Query query = getNamedQuery("Person.findSpecific",Person.class);

但这又不会将其映射到Person类.

But that again does not map it to Person class.

推荐答案

您可以使用构造函数表达式:

select new my.app.PersonView(p.name, p.age) from Person p ...

在这种情况下,对于结果中的每一行,都会创建一个新的PersonView实例.

In this case, for every line in the result, a new PersonView instance is created.

请注意,此实例未连接到数据源(它们不受管理),因此您将无法通过修改实例来更改基础数据.

Note that this instances are NOT connected to the data source (they are not managed), so you will not be able to change the underlying data by modifying the instances.

这就是为什么我建议不要在构造函数表达式中使用实体类,以免它们与真实"实体混淆.而是编写仅携带数据的自定义传输对象".每种投影一个定制的类,或者-如果需要在同一实体上进行许多不同的投影,则-一个更大的类,其中有多个构造函数用于所有投影.在这种情况下,某些字段将始终为空.

That's why I suggest to NOT use entity classes in constructor expressions to not mix them up with 'real' entities. Instead write custom 'transfer objects' that only carry the data. Either one tailored class per projection or - if many different projections on the same entity are required - one bigger class with multiple constructors that is used for all projections. In that case, some fields will always be empty.

这篇关于带有显式自定义类的getNamedQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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