Hi everybody,
I can't figure out the reason why I get this behavior:
A part of my data model consist of two tables, Authorities and Definitions
Code:
------------- 1 * --------------
|Authorities| <----------- | Definitions |
------------- ---------------
Code:
My annotations for Definitions look like:
@ManyToOne
@JoinColumn(name="AUTHORITY_ID")
public Authority getAuthority() {
return authority;
}
and for Authority:
Code:
@Table(
name="AUTHORITIES",
uniqueConstraints = @UniqueConstraint(columnNames={"SERVER_NAME","DOMAIN_LABEL"})
)
public class Authority {
...
@Id(generate = GeneratorType.IDENTITY)
@Column(name = "AUTHORITY_ID")
public int getAuthorityId() {
return authorityId;
}
The problem arise when I try to do the following:
Code:
Authority a = sampleAuthority();
getSession().save(a);
ProbeDefinition p = sampleDefinition();
p.setAuthority(a);
getSession().save(p);
//now p.getAuthority.getAuthorityId() has been set
Criteria c = getSession().createCriteria(ProbeDefinition.class)
.add(Restrictions.eq("authority", p.getAuthority())));
List ret = c.list();
assertTrue(ret.contains(p));
In this form (saving p and querying for the same) everything works BUT it does not if I pretend to make the criteria with a new instance of ProbeDefinition (transient).
In fact in this case when list() is called I get the exception:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: net.ripe.dnsmon.conf.vo.Authority
It happens that the generated sql query joins on AUTHORITY_ID which for the transient Authority instance is set to 0... So it's ok that I get the error.
The point is that my Authority implements equals() and hashCode() so
that they don't depend on the id but only on the two column specified in the @UniqueConstraint. Then why then Restrictions.eq is using the authorityId to make the join???
I was expecting the constraint eq() to use object equality but it seems it's not.
So I guess that I have to write the join by hand...
But still I'd like to know if this is the correct behavior or if I'm missing something
Thanks a lot, and merry christmas for everyone:D
Francesco
Hibernate version:3.1
Name and version of the database you are using:
hsqldb 1.8