我在研究2小时后创造了这个主题。
我正在尝试做一个非常简单的汽车位置代码,可以保存,从数据库中删除获取数据。
所以我的问题是我有一个名为Vehicule的父类和2个子类:car和van。 下面是我的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
}
我将它们存储在一个包含inheritanceStratregy = single table的表中。 现在,我想只选择汽车或只选择货车。
我试过
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
我做错了什么?
提前致谢!
答案 0 :(得分:0)
我无法看到你的&#34; Vehicule&#34;的完整领域。实体。 但是如果你在Vehicule表上有一个字段名称&#34; vehicule_type&#34; 您必须在代码中使用名称&#34; vehiculeType&#34;
指定它试着改变&#34; vehicule_type&#34; to&#34; vehiculeType&#34;
但是为了获得更多帮助,我认为您必须提供Vehicle实体类的内容。
干杯
答案 1 :(得分:0)
是否有任何名为vehicule_type的字段?我怀疑它不存在,不知何故你试图访问它导致异常。
答案 2 :(得分:0)
您永远不需要插入鉴别器值的标准。 JPA自己这样做。您只需选择正确的实体。
在您的情况下,您应该选择:“SELECT v FROM Car v”。 如果在配置中启用show_sql,您将看到JPA自动添加aliasXX.vehicule_type ='Car'