I have two classes. One is the entity class, the other serves as a composite key class.
The code is as followed.
@Entity public class Supply { @Embeddable class Id implements Serializable { @Column(name = "supplier_id") private long supplierId; @Column(name = "merchandise_id") private long merchandiseId; public Id() { } public Id(long sId, long mId) { this.supplierId = sId; this.merchandiseId = mId; } } @EmbeddedId private Id id = new Id(); }
If I use try to find
from Supply where merchandise_id=%d and supplier_id=%d
Hibernate will throw an exception,namely:
No default constructor for entity: com.entity.Supply$Id; nested exception is org.hibernate.InstantiationException: No default constructor for entity: com.entity.Supply$Id
However, I found that if I change class Id to static. Everything will be fine.
I am just curious about how all these stuff can happen.
Though, In the case of Hibernate Persistent classes or Entities, it's must to provide a no argument constructor, so that Hibernate can create instance of Persistence classes, when you hibernate load them from database. It also uses newInstance() method to create instance of persistent classes.
hibernate. InstantiationException: No entity default constructor. The default constructor is a method of the constructor without any argument invoked when creating an instance of the class. Hibernate uses default construction to create bean object using reflections.
Reason: Default constructor is required to have Hibernate initialize the entity; private is allowed but package private (or public) visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.
Implement a default constructor. Cat has an implicit default (no-argument) constructor. All persistent classes must have a default constructor (which may be non-public) so Hibernate can instantiate them using Constructor. newInstance().
If the class is not static
, it requires an instance of the outer class in order to be instantiated - so there will be no default constructor. You'd have to use syntax similar to:
new Supply().new Id();
If the Id
class is static
, you can just call:
new Id();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With