My problems come from the fact that I am trying to reuse a mapped superclass that contains some basic fields such as a Long Id. This mapped superclass looks like this:
@MappedSuperclass
public abstract class AbstractBaseEntity {
protected Integer id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id", nullable = false, unique = true, columnDefinition = "int")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
It sits in a jar so that everyone can reuse it easily. Apparently, all works perfectly except when entities that extend it actually have relationships between them and you try to get data using queries based on those relationships. Example: Say you have entity Organization that has one or more User (s):
@Entity
@Table(name = "Organizations")
public class Organization extends AbstractBaseEntity {
private Set<User> users;
@OneToMany(mappedBy = "organization", fetch = FetchType.LAZY)
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
@Entity
@Table(name = "Users")
public class User extends AbstractBaseEntity {
private Organization organization;
@ManyToOne
@JoinColumn(name = "Organization_ID", nullable = false)
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Now here's the problem: If I use a DETACHED organization object as a parameter to a query like this:
SELECT u from User u where u.organization = ?1
then Hibernate throws this following exception:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.Organization
This doesn't make any sense to me, it shouldn't require an attached entity for this kind of query since all it needs is its id.
If, however, i take out AbstractBaseEntity from the jar and put it in the same project as Organization and User, it all works perfectly, with detached Organizations and all...
This looks very much like a bug to me. Any clues on how to work around it?
PS. I've tried explicitly specifying the AbstractBaseEntity as a class in persistence.xml as specified here - JPA @MappedSuperclass in separate JAR in Eclipse (weird but worth a try) ...doesn't work