I have a problem with mapping a list of subclasses:
Model situation - I have an abstract class:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="shapeType",
discriminatorType=DiscriminatorType.STRING
)
public abstract class Shape{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Long id;
@Column(name="owner_id")
private Long ownerId;
@ManyToOne
@JoinColumn(updatable=false, insertable=false, name="owner_id")
private Owner owner;
}
and its subclasses:
@Entity
@DiscriminatorValue(value="triangel")
public class Triangel extends Shape {
}
and:
@Entity
@DiscriminatorValue(value="circle")
public class Circle extends Shape {
}
Then, I have a class Owner
, which has a list of subclasses:
@Entity
public class Owner {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", targetEntity=Shape.class)
private List<Triangel> triangels;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", targetEntity=Shape.class)
private List<Circle> circles;
}
When I loop over the triangel
list:
for(Object triangel: owner.getTriangels()){ //Using Triangel as a type throws ClassCastException
logger.info(triangel.toString());
}
it iterates all shapes objects, not just triangel
objects. It seems to me, that hibernate ignores DiscriminatorColumn
during the selection subclasses in that situation.
Mind, that without specification targetEntity
as Shape.class
in @OneToMany
, my application did not even start and had some problem with mapping initialization.
Configuration from pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
<scope>provided</scope>
</dependency>
How am I supposed to do correct mapping configuration of that design?