使用JPA查询部分实体 [英] Query partial entities with JPA

查看:161
本文介绍了使用JPA查询部分实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的JPA实体;

I have a JPA entity similar to;

public class Inventory {
 private String productname;
 private String manufacturer;
 private Float retailprice;
 private Integer unitssold;
 private String ourcomment;
}

在大约2/5的查询中,我需要整个实体,但其余的当我 unitssold 我们的评论感兴趣的时候。

In about 2 out of 5 queries I need the whole entity, but the rest of the time I am not interested in unitssold and ourcomment.

感觉像浪费一样进行查询并得到一个大的结果列表,但只需要3/5的信息。我想稍微优化一下,我有预感这可以使用继承。

It feels like a waste to make a query and get a large resultlist but only needing 3/5 of the information. I would like to optimize this slightly, and I have a hunch this can be done using inheritence.

但是如何?

推荐答案

继承?否。

即使假设您的实际域名实体包含列表中的前三个字段且库存会扩展它,由于隐式多态性,你对该实体所做的任何查询都将不可避免地加载所有字段(通过连接,如果映射到不同的表)。

Even assuming you've had an actual domain entity that consisted of first three fields on your list and Inventory would have extended it, any query you would have made against that entity would inevitably load all fields (via join if mapped to a different table) due to implicit polymorphism.

你可以做的是将第4和第5个属性映射为懒惰;你的JPA提供者必须使用字节码检测才能做到这一点:

What you can do is map the 4th and 5th properties as "lazy"; your JPA provider will have to employ bytecode instrumentation in order to be able to do that:

@Basic(fetch = FetchType.LAZY)
private Integer unitssold;

@Basic(fetch = FetchType.LAZY)
private String ourcomment;

您必须指定获取所有属性在需要获取所有内容的查询中;其他人在第一次访问之前不会检索属性值。

You'll have to specify fetch all properties in queries where you need to fetch everything; others will not retrieve property value until first accessed.

老实说,如果你的查询返回大的结果集并且懒惰属性相当大,这种方法是值得的他们自己(例如我不会单独为整数; 字符串如果它可以变长可能是可行的)

To be honest, this approach is only worth it if your queries return large result sets and "lazy" properties are rather big themselves (e.g. I wouldn't do it for Integer alone; String may be feasible if it can get long)

这篇关于使用JPA查询部分实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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