Suppose we have:
Code:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(schema = "scott", name = "tb_animal")
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "brand")
@SequenceGenerator(name = "mysequence", allocationSize = 1, sequenceName = "sq_animal")
public class Animal implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mysequence")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Code:
@Entity
@DiscriminatorValue("cat")
@SecondaryTable(
pkJoinColumns = {@PrimaryKeyJoinColumn(name = "pk_animal", referencedColumnName = "id")},
schema = "scott", name = "tb_cat"
)
public class Cat extends Animal {
@Column(name = "color", table = "tb_cat")
private String color;
@Column(name = "name", table = "tb_cat")
private String name;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and
Code:
@Entity
@DiscriminatorValue("dog")
@SecondaryTable(
pkJoinColumns = {@PrimaryKeyJoinColumn(name = "pk_animal", referencedColumnName = "id")},
schema = "scott", name = "tb_dog"
)
public class Dog extends Animal {
@Column(name = "race", table = "tb_dog")
private String race;
@Column(name = "weight", table = "tb_dog")
private Float weight;
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
public Float getWeight() {
return weight;
}
public void setWeight(Float weight) {
this.weight = weight;
}
}
Well the mapping works fine, and "joined subclasses" are simulated and there also exists a "discriminator column".
But a problem remains, when I execute
from Animal query, all tables are joined together in resulting SQL query!
Is there any way to hibernate create 2 queries (one only on
tb_animal and one on
tb_cat or
tb_dog) according to discriminator values?
The problem is in our project we have a complex heirarchy which is mapped on more than 20 tables! When I execute something like
from Animal ax where ax.id = ? a complex and slow query is exexuted....