jacekn
jacekn

Reputation: 1541

How to map JPA discriminator value?

I believe I had this working and I must have done something. Hopefully, someone can see the issue right away.

Two classes in an inheritance relationship. Two tables in play. Both tables receive records. Issue at hand: discriminator value not stored.

Parent Class

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="entp", discriminatorType=DiscriminatorType.STRING)
@Table(name="enrg")
public abstract class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)   
    @Column(name="enid")
    private Long entityId;

    // some string property mapped to column 'nm;
    // some string property mapped to column 'ns;
    // some string property mapped to column 'tmcr;

Child Class

@Entity
@DiscriminatorValue("ws")
@Table(name="ws")
public class Website extends BaseEntity {
    private static final long serialVersionUID = 1L;

    @Column(name="exdr", length=100)
    private String exportDirectory;

Service call

getEntityManager().persist(website);

SQL

Hibernate: insert into enrg (nm, ns, tmcr) values (?, ?, ?)
Hibernate: insert into ws (exdr, enid) values (?, ?)

Hibernate

<persistence-unit name="prod" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>prodDataSource</jta-data-source>

    <class>webadmin.domain.core.Website</class>

    <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
        <property name = "hibernate.show_sql" value = "true" />
        <property name = "hibernate.discriminator.ignore_explicit_for_joined" value = "false" />
    </properties>

</persistence-unit>

What do I need to do, to have Hibernate include entp column/value in the insert for enrg? In this case, entp value should be 'ws'.

Solution

All my mappings/configuration remains, as above. I have upgraded to Hibernate 4.3.6 and under TomEE 1.7 this now works.

Hibernate: insert into enrg (nm, ns, tmcr, entp) values (?, ?, ?, 'ws')
Hibernate: insert into ws (exdr, enid) values (?, ?)

Upvotes: 1

Views: 4088

Answers (1)

Ankur Singhal
Ankur Singhal

Reputation: 26067

does this and this help you.

In the end only SINGLE_TABLE strategy requires a discriminator column, JOINED can be implemented without. The problem with Hibernate currently is that it causes inconsistent data when persisting sub entities in a JOINED inheritance mapped with @DiscriminatorColumn, even though the JPA spec recommends to persist discriminator values if a discriminator is used with JOINED.

Upvotes: 1

Related Questions