jpa原生query_带有继承的JPA原生查询实体

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

@Entity

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

public class A

and

@Entity

public class B extends 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()

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()

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?

解决方案

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. Handling inheritance

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.

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()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值