具有继承性的实体的 JPA 本机查询 [英] JPA Native Query for Entity with Inheritance

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

问题描述

我有一个实体类和一个基于该实体的子类:

I have an entity class and a subclass based on that entity:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class A

@Entity
public class B extends A

我需要发出一个只在基类 (A) 上使用存储过程的本机查询.如果我尝试如下:

I need to issue a native query that uses a stored procedure on the base class (A) only. If I attempt it as follows:

entityManager.createNativeQuery("select * from A a where procedure(f)",A.class).getResultList()

我收到有关在结果集中未找到 clazz_ 列"的错误消息.我假设 JPA 提供程序添加此列是为了区分基类和扩展类.我可以通过显式添加 clazz 列和子类中的所有字段来解决此问题:

I get an error regarding "The column clazz_ was not found in the ResultSet". I assume that the JPA provider adds this column in order to discriminate between the base class and the extended class. I can work around this problem by explicitly adding the clazz column and all of the fields from the subclass:

entityManager.createNativeQuery("select *,1 as clazz_,null as prop1,null as prop2 from A a where procedure(f)",A.class).getResultList()

其中prop1"和prop2"是子类 B 的属性.然而,这似乎是不必要的黑客攻击,并且如果子类 B 更改,则容易出现维护问题.

where "prop1" and "prop2" are properties of the subclass B. However, this seems like an unnecessary hack and is prone to maintenance problems if the subclass B changes.

我的问题是:如何在定义了继承的实体上使用存储过程进行查询?

My question is: How can I query using a stored procedure on an entity that has inheritance defined on it?

推荐答案

正如您可能已经看到的,Hibernate 团队并没有投入大量工作来定义您如何执行此操作.文档只是声明:

As you've probably seen, the Hibernate team hasn't put a lot of work into defining how you do this.. the documentation simply states:

><块引用>

16.1.6.处理继承

16.1.6. Handling inheritance

查询的本机 SQL 查询作为一部分映射的实体继承必须包括所有基类和所有的属性它的子类.

Native SQL queries which query for entities that are mapped as part of an inheritance must include all properties for the baseclass and all its subclasses.

因此,如果您想使用本机查询,那么您似乎无法执行此类操作.关于子类 B 更改的担忧,也许实现这一点的一种稍微不那么繁琐的方法是尝试在共享 ID 属性上使用 LEFT OUTER JOIN 语法:

So if you want to use Native queries it looks like you're stuck doing something like this. Regarding the concern about the subclass B changing, perhaps a slightly less onerous way of implementing this would be to try using LEFT OUTER JOIN syntax on the shared ID property:

entityManager.createNativeQuery("select a.*, b*, 1 as clazz_, from A a LEFT OUTER JOIN B b on id = a.id where procedure(f)",A.class).getResultList()

这样,如果您添加或删除一些属性,您将始终从 B 获得所有属性.

That way you'll always get all of the properties from B if you add or remove some.

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

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