【问题标题】:JPA select queryJPA 选择查询
【发布时间】:2017-04-25 04:25:27
【问题描述】:

经过 2 小时徒劳的研究,我正在创建这个主题。

我正在尝试做一个非常简单的汽车位置代码,它可以保存、从数据库中删除获取数据。

所以我的问题是我有一个名为 Vehicule 的父类和 2 个子类:汽车和货车。 下面是我的3堂课的开始

// vehicule
@Entity
@Table(name="Vehicule")
@DiscriminatorColumn(name="vehicule_type")
@Inheritance
public class Vehicule implements Serializable{
// some constructors setters and getters here
}

// car
@Entity
@DiscriminatorValue("Car")
public class Car extends Vehicule{  
    @Column(name = "number_of_seats")
    private int nbOfSeats;
    // some constructors setters and getters here
}

// van
@Entity
@DiscriminatorValue("Van")
public class Van extends Vehicule{
    @Column(name = "max_weight")
    private int maxWeight;
    // some constructors setters and getters here
}

我将它们存储在一个表中,继承策略 = 单个表。 现在,我想只选择汽车或货车。

我试过了

Query query = em.createQuery("SELECT v FROM Vehicule v WHERE v.vehicule_type = 'Car'");
List<Car> list = (List<Car>) query.getResultList();

但我明白了

Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
The state field path 'v.vehicule_type' cannot be resolved to a valid type.

我也试过了

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Car> q = cb.createQuery(Car.class);
Root<Car> c = q.from(Car.class);
ParameterExpression<String> p = cb.parameter(String.class);

q.select(c).where(cb.equal(c.get("vehicule_type"), p));

TypedQuery<Car> query = em.createQuery(q);
query.setParameter(p, "Car");
List<Car> results = query.getResultList();

但我明白了

Caused by: java.lang.IllegalArgumentException: The attribute [vehicule_type] is not present in the managed type

我做错了什么?

提前致谢!

【问题讨论】:

  • 您不需要在标准中附加vehicule_type。 JPA 自行附加它,因为您说 select from Vehicule... 尝试 SELECT v FROM Vehicule v

标签: java sql jpa jpql discriminator


【解决方案1】:

我看不到您的“车辆”实体的完整字段。 但是,如果您的车辆表上有一个字段名称“vehicule_type” 您必须在代码中使用名称“vehiculeType”指定它

只需尝试将“vehicule_type”更改为“vehiculeType”

但是为了更多的帮助,我认为你必须提供你的Vehicle实体类的内容。

干杯

【讨论】:

    【解决方案2】:

    是否有名称为vehicule_type 的字段?我怀疑它不存在,并且您试图以某种方式访问​​它导致异常。

    【讨论】:

      【解决方案3】:

      您永远不需要为鉴别器值插入 where 条件。 JPA 自己做这件事。你只需要选择正确的实体。

      在您的情况下,您应该只选择:“SELECT v FROM Car v”。 如果您在配置中打开 show_sql,您将看到 JPA 自动添加 where aliasXX.vehicule_type = 'Car'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-26
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-05
        • 2021-12-14
        • 2017-01-23
        相关资源
        最近更新 更多