I'm using Hibenate with a legacy database (of which i cannot change the schema). Now i got the typical problem: As the old programs don't know about NULL and there's no referential integrity, they use a 0 (zero) in the foreign key instead.
Code:
@Entity
@IdClass(TeamId.class)
public class Team implements Serializable {
@Id
@Column(name = "PTFANR")
private short fanr;
@Id
@Column(name = "PTTNUM")
private short teamnr;
@OneToMany(mappedBy = "team", fetch = FetchType.LAZY)
@Fetch(FetchMode.SUBSELECT)
private Set<Personal> teamMembers = new HashSet<Personal>();
...
}
@Entity
@IdClass(PersonalId.class)
public class Personal implements Serializable
{
@Id
@Column(name = "PEFANR")
protected short fanr;
@Id
@Column(name = "PEPENR")
protected short penr;
@Column(name = "PETNUM")
protected short tnum;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({
@JoinColumn(name="PEFANR", referencedColumnName="PTFANR", insertable = false, updatable = false),
@JoinColumn(name="PETNUM", referencedColumnName="PTTNUM", insertable = false, updatable = false)
})
@NotFound(action=NotFoundAction.IGNORE)
private Team team;
...
}
As you can see, i worked around the problem with the @NotFound annotation. This works ok, but when i looked at the generated SQL statements i saw that for every row with a zero foreign key it generated a seperate select! So when loading all Personal records (~500), i generated a lot of additional selects.
First question: Why all these selects? Hibernate already does a left outer join!
Second: Is there a better way to handle this situation? I used a UserType on other tables, but this is a composite foreign key. Is a CompositeUserType possible here?
Thanks in advance for any help/clearification