Search code examples
jakarta-eejpajava-ee-6jpql

JPA JPQL query, where object1 = object2


Query1 (Works fine!!!):

em.createQuery(
            "SELECT r FROM Route r WHERE r.start.x = :x"
            , Route.class).setParameter("x", start.getX())

Query2 (id really like this one to work!):

   em.createQuery(
            "SELECT r FROM Route r WHERE r.start = :x"
            , Route.class).setParameter("x", start)
            .setMaxResults(20)

Throws: TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Route Entity:

 @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;
}

}

Location:

@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;
}

}


Solution

  • TransientObjectException was thrown when Class that was instantiated via constructor was being compared with same object of the same Class read from Database. Since Class Route is annotated as @Entity, query has considered the first object to be transient (as it had no @id field set).