Query1(工作正常!!!):
em.createQuery(
"SELECT r FROM Route r WHERE r.start.x = :x"
, Route.class).setParameter("x", start.getX())
Query2(id真的很喜欢这个!):
em.createQuery(
"SELECT r FROM Route r WHERE r.start = :x"
, Route.class).setParameter("x", start)
.setMaxResults(20)
抛出: TransientObjectException:对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例
路线实体:
@Entity
@XmlRootElement(name="route")
@XmlAccessorType(XmlAccessType.NONE)
public class Route {
private Long id;
private User user;
private Location start;
private Location finish;
public Route() {
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne
@JoinColumn
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@OneToOne(cascade=CascadeType.PERSIST)
public Location getStart() {
return start;
}
public void setStart(Location start) {
this.start = start;
}
@OneToOne(cascade=CascadeType.PERSIST)
public Location getFinish() {
return finish;
}
public void setFinish(Location finish) {
this.finish = finish;
}
}
位置:
@Entity
public class Location {
@Id
@GeneratedValue
private Long id;
private double x;
private double y;
public Location() {
}
public Location(double x, double y) {
this.x = x;
this.y = y;
}
@XmlTransient
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public boolean equals(Object o) {
if ((o instanceof Location)
&& (((Location)o).getX() == this.x)
&& (((Location)o).getY() == this.y))
{
return true;
}
else return false;
}
}
答案 0 :(得分:1)
该异常与查询本身没有多大关系。
抛出它是因为在执行查询之前,Hibernate会刷新尚未刷新的更改。并且不能这样做因为...一个对象引用一个未保存的瞬态实例。因此,请确保在执行查询之前保存瞬态实例。
答案 1 :(得分:0)
当通过构造函数实例化的Class与从数据库读取的同一类的同一对象进行比较时,抛出了TransientObjectException。由于Class Route注释为@Entity,因此查询认为第一个对象是瞬态的(因为它没有设置@id字段)。