【问题标题】:Get superclass field value using JQPL query in JPA在 JPA 中使用 JPQL 查询获取超类字段值
【发布时间】:2017-03-16 16:00:26
【问题描述】:

假设我有一个名为 Vehicle 的超类,如下所示:

@Entity
public class Vehicle {
    private LocalDateTime dateTimeOfCreation;
}

而且,假设我有一个名为 Car 的子类,如下所示:

    @Entity
    public class Car extends Vehicle{
    }

而且,我有一个我想选择在某个日期之后创建的所有汽车。而且,虽然dateTimeOfCreation 字段在超类中,但我需要能够查询子类,因为我不容易解释。

我试过这个查询:SELECT c from Car c WHERE c.dateTimeOfCreation > :dateTime

但是,我收到 ORA-00904: Invalid Identifier 错误,这在某种程度上是合乎逻辑的,因为类 car 没有该字段和 Cars。另外,我使用的是 JOINED INHERITANCE,所以每个类都有它的表,dateTimeOfCreation 存储在 Vehicle 表中。这是我无法改变的,原因又很难解释。

编辑:我给出的代码只是一个例子。事实上。 Vehicle 是我不应该更改的框架的一部分,因此它已经具有 @Entity 注释。

Car 是我实现的一个类,它也需要是一个实体。但是,该框架会跟踪创建时间,我需要在查询中使用该信息。但是,我不能直接查询 Vehicle,因为我只需要汽车,而不是卡车、自行车等。

【问题讨论】:

    标签: java jpa inheritance jpql


    【解决方案1】:

    您将Vehicle 声明为实体,因为您已使用javax.persistence.Entity 对其进行了注释。您不应该,否则您应该将其声明为抽象类。

    您还可以通过使用javax.persistence.MappedSuperclass 注释来注释Vehicle 类来指定映射的超类。

    例如:

    @MappedSuperclass
    public class Vehicle {
        private LocalDateTime dateTimeOfCreation;
    }
    

    如果您不想查询 Vehicle 实体,该解决方案适用。

    【讨论】:

    • 感谢您的回复。但是,不幸的是,就我而言,它不能那样做。请看我的更新。
    【解决方案2】:

    类车辆

    @Entity(name = "vehicle")
        @Inheritance(strategy= InheritanceType.JOINED)
        public class Vehicle {
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            private Long id;
    
            private LocalDateTime dateTimeOfCreation;
    
            public void setId(Long id) {
            this.id = id;
            }
    
            public Long getId() {
                return id;
            }   
    
            public Date getDateTimeOfCreation() {
                return date;
            }
    
            public void setDateTimeOfCreation(Date date) {
                this.date = date;
            }
        }
    

    类车:

    @Entity(name = "car")
    @PrimaryKeyJoinColumn(name = "vehicle_id")
    public class Car extends Vehicle {
    
    }
    

    道类:

    public class Abc {
      -----your logic-----
    Session session = HibernateUtil.getSession();
            Query query = session.createQuery("from car as c where c.dateTimeOfCreation >= :date");
            query.setParameter("date", LocalDateTime.now());
            List<RegularEmployee> regularEmployees = query.list();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 2013-04-23
      • 2017-05-23
      • 2015-08-05
      • 2017-11-30
      • 2017-11-28
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多