我的超类是:
@Entity
@Table(name = "TEST_VEHICLE")
@ChangesListener
@AttributeOverride(name = "id", column = @Column(name = "VEHICLE_ID"))
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "VEHICLE_TYPE_ID", discriminatorType = DiscriminatorType.INTEGER)
public abstract class Vehicle extends ParentEntity {
@Column(name = "MAX_SPEED", nullable = false)
private Integer maxSpeed;
public Integer getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(Integer maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
和子类是:
@Entity
@Table(name = "TEST_BUS")
@DiscriminatorValue("2")
public class Bus extends Vehicle {
@Column(name = "PASSENGER_NUMBER", nullable = false)
private Short passengerNumber;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "FOO_OF_VEHICLE")
private Foo foo;
public Short getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(Short passengerNumber) {
this.passengerNumber = passengerNumber;
}
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
}
在条件中使用foo
上的Root<Vehicle>
获取
root.fetch("foo", JoinType.LEFT);
导致此错误:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [foo] on this ManagedType ...
如何从子类中获取字段?
更新
使用treat不能解决我的问题:
Root<Bus> busRoot = builder.treat(root, Bus.class);
busRoot.fetch("foo", JoinType.INNER);
我没有收到任何错误,但是foo还没有收到。 生成的SQL是:
SELECT vehicle0_.VEHICLE_ID AS VEHICLE_2_72_,
vehicle0_.ATTACHMENT_COUNT AS ATTACHME3_72_,
vehicle0_.COMMENTS AS COMMENTS4_72_,
vehicle0_.CREATE_TIMESTAMP AS CREATE_T5_72_,
vehicle0_.CREATOR_USER_ID AS CREATOR_8_72_,
vehicle0_.MODIFIER_USER_ID AS MODIFIER9_72_,
vehicle0_.UPDATE_TIMESTAMP AS UPDATE_T6_72_,
vehicle0_.MAX_SPEED AS MAX_SPEE7_72_,
vehicle0_1_.FOO_OF_VEHICLE AS FOO_OF_V3_70_,
vehicle0_1_.PASSENGER_NUMBER AS PASSENGE1_70_,
vehicle0_2_.ENGINE_TYPE AS ENGINE_T1_71_,
vehicle0_.VEHICLE_TYPE_ID AS VEHICLE_1_72_
FROM TEST_VEHICLE vehicle0_
LEFT OUTER JOIN TEST_BUS vehicle0_1_
ON vehicle0_.VEHICLE_ID=vehicle0_1_.VEHICLE_ID
LEFT OUTER JOIN TEST_CAR vehicle0_2_
ON vehicle0_.VEHICLE_ID =vehicle0_2_.VEHICLE_ID
WHERE vehicle0_.VEHICLE_ID=105
答案 0 :(得分:1)
使用元模型可以解决这个问题。
public abstract class Bus_ extends com.rh.cores.architecture.tests.models.Vehicle_ {
public static volatile SingularAttribute<Bus, Foo> foo;
public static volatile SingularAttribute<Bus, Short> passengerNumber;
}
意味着:
root.fetch(Bus_.foo, JoinType.LEFT);
但由于JPA中的提取签名是这样的:
<Y> Fetch<X, Y> fetch(SingularAttribute<? super X, Y> attribute, JoinType jt);
上面的代码导致编译错误! 改变这样的代码:
SingularAttribute attribute = Bus_.foo;
root.fetch(attribute, JoinType.LEFT);
我们可以在JPA标准中绕过泛型检查SingularAttribute<? super X, Y>
,而Hibernate处理它!