Search code examples
inheritancejpasingle-table-inheritance

JPA single table inheritance could not load correct object


I have these 2 classes:

@Entity
@Table(name = "S_MC_CC_CLIENTI")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="COD_TIPOCLIENTE")
@DiscriminatorValue("PF")
public class Cliente implements Serializable {
...
}

@Entity
@DiscriminatorValue("PM")
public class ClienteMinore extends Cliente {

    @Override
    public String toString() {
        return new ToStringCreator(this).append("cliente=" + super.toString()).toString();
    }
}

This test try to load the objects.

@Test
    public void testGetItemPersonaFisica() {
        EntityManager entityManager = factory.createEntityManager();
        entityManager.getTransaction().begin();

        Cliente.ClienteId clienteId = new Cliente.ClienteId(codiceAbi, btUtenteProfilo);        

        Cliente cliente = entityManager.find(Cliente.class, clienteId);
        assertNotNull(cliente);
        System.out.println(cliente);
        System.out.println(cliente.getTipologiaCliente());

    }

First test: on DB for that record with COD_TIPOCLIENTE=PF all works great. But when I change the value with COD_TIPOCLIENTE=PM I got an error since the query triggered from JPA is:

SELECT * FROM S_MC_CC_CLIENTI WHERE (((COD_ABI = ?) AND (ANAG_UTENTE = ?)) AND (COD_TIPOCLIENTE = ?))
bind => [01025, 71576493, PF]

It seems that the generated query is wrong since the key is [01025, 71576493] while the PF should be the value of the discriminator columns.

Any idea how to fix the problem?

Kind regards Massimo


Solution

  • I found the problem. I forgot to insert the subclass reference in the persistence unit descriptor.

    All works great now.

    Massimo