Search code examples
javahibernateenumshibernate-mappinginstantiation

org.hibernate.InstantiationException: No default constructor for entity: com.domaine.AnomalieAck


I am trying to persist an enum Value into the database, but an instantiation exception is triggered, here is my mapping :

@Entity
public class Anomalie {

    @Embedded
    private AnomalieAck ack = AnomalieAck.NON_ACQUITTEE;



    public Anomalie() {
    }
/*getters and setters*/
}

//AnomalieAck.java

public enum AnomalieAck {

    NON_ACQUITTEE(0),

    ACQUITTEE_APP1 (1),

    ACQUITTEE_APP2(2),

    /** Aacquittee en erreur. */
    ACQUITTEE_ERREUR(10),

    @Column(name = "ANO_ACK")
    private int ack = 0;

  private AnomalieAck() {

    }

  private AnomalieAck(final int value) {
    this.ack = value;
   }
  public int getValue() {
        return this.ack;
    }
  public void setAck(int ack) {
        this.ack = ack;
    }
}

The reason why I didn't use the @Enumerated(EnumType.STRING) or @Enumerated(EnumType.ORDINAL) is that in the database the field ANO_ACK is declared as the number and there are a lot of other resources that use this value as Number.

I have checked everything: the no-args constructor is already defined, the setter method is implemented.

What can I do to let Hibernate instantiate this class?


Solution

  • Do not embed an enum.

    What you need here is a custom converter:

    Converter:

    @Converter
    public class AnomalieAckConverter implements AttributeConverter<AnomalieAck , Integer> {
    
     @Override
     public String convertToDatabaseColumn(AnomalieAck  anomalieAck ) {
       return anomalieAck.getValue();
     }
    
     @Override
     public AnomalieAck convertToEntityAttribute(Integer ack) {
        retrun AnomalieAck.getByValue(ack);
     }
    
    }
    

    Entity:

    @Column
    @Convert(converter = AnomalieAckConverter.class)
    private AnomalieAck ack;