Hello,
I'm new to Hibernate, and so far I'm liking it very much. It makes my work easy and sound. Kudos for that.
I'm trying to map a legacy database (a very old one, with some bad idiosyncrasies) using Hibernate Annotations, and I've encountered this problem:
I've got a table T1 with two fields F1 and F2 which are the foreign key for a table T2 (primary key is made by F1 and F2).
More specifically, F1 is a string and not a problem, F2 is an integer; if it is set to 0 I should not do the join between tables. This is because I want to model a 0..1 multiplicity.
Thus, creating an object of type O1, I've first mapped O2 to T2; I've used a static inner class to represent the composite primary key, and then @EmbeddedId to annotate the corresponding field of O2 in the code. So far, so good.
I want now to have a many-to-one relationship from O1 to O2, however as I said if F2 is 0, then the reference o2 inside an instance of O1 should be null.
This is the code of O2:
Code:
@Entity
@Table (name="T2")
public class O2
{
public static class T2Id implements Serializable
{
private String f1;
private Integer f2;
O2 () {}
public O2 (String f1, Integer f2)
{
this.f1 = f1;
this.f1 = f2;
}
@Override
public int hashCode ()
{
return code.hashCode () + pos.hashCode ();
}
@Override
public boolean equals (Object o)
{
if (o == null) return false;
if (!(o instanceof T2Id)) return false;
T2Id d = (T2Id) o;
return f1.equals (d.f1) && f2.equals (d.f2);
}
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "f1",
column = @Column(name="F1")),
@AttributeOverride(name = "f2",
column = @Column(name="F2"))
})
private T2Id id;
Now, inside O1, I've written this:
Code:
@Entity
@Table (name="T1")
class O1
{
// ... more code
@ManyToOne (optional=true, fetch=FetchType.LAZY)
@JoinColumns({
@JoinColumn (name="F1", insertable=false, updatable=false),
@JoinColumn (name="F2", insertable=false, updatable=false)
})
@WhereJoinTable (clause="F2 != 0 and F2 Is Not Null")
private O2 o2;
}
However, I can't have Hibernate do the right thing. It always throws an EntityNotFoundException (and rightly so, since it tries to instantiate O2 objects with f2 == 0).
Instead, I'd like that, when the @WhereJoinTable clause is not met, o2 == null.
How can I achieve the wanted result? Thanks in advance!