JPA本机SQL查询映射错误?

时间:2017-08-24 14:30:15

标签: java oracle jpa native-sql

我有一个JPA实体MyEntity,其中包含@EmbeddableMyEntityPK中的复合主键。
我在方法getThreeColumnsFromMyEntity()中使用本机SQL查询:

 public List<MyEntity> getThreeColumnsFromMyEntity() {

  List<MyEntity> results = em.createNativeQuery("select  pid,name,dateofbirth from (select pid,name, dateofbirth,max(dateofbirth) "
            + "over(partition by pid) latest_dateofbirth from my_entity_table) where"
            + " dateofbirth = latest_dateofbirth;","myEntityMapping").getResultList();

    return results;

我的@SqlResultSetMapping

@SqlResultSetMapping(
    name = "myEntityMapping",
    entities = {
        @EntityResult(
                entityClass = MyEntityPK.class,
                fields = {
                    @FieldResult(name = "PID", column = "pid"),
                    @FieldResult(name = "NAME", column = "name")}),
        @EntityResult(
                entityClass = MyEntity.class,
                fields = {
                    @FieldResult(name = "dateofbirth", column = "dateofbirth")})})

我的JPA列名为:@Column(name="DATEOFBIRTH")"PID""NAME" 我直接在db上测试了我的sql语句,它运行正常 当我在Eclipse上运行它时出现Oracle错误:

  

ORA-00911和“错误代码911,查询:ResultSetMappingQuery [..]

我的猜测是映射有问题,但我找不到它是什么。

1 个答案:

答案 0 :(得分:1)

我假设您收到此错误,因为您缺少子查询的别名,所以您可以尝试这样做:

select
   pid,
   name,
   dateofbirth 
from
   (
      select
         pid,
         name,
         dateofbirth,
         max(dateofbirth) over(partition by pid) AS latest_dateofbirth 
      from
         my_entity_table
   ) second_result 
--        ^--------------- use an aliase name to the subquery 
where
   second_result.dateofbirth = latest_dateofbirth
--  ^----use the aliase name to reference to any of its fields, in your case 'dateofbirth' 

在这里查看错误含义ORA-00911: invalid character tips