Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No default constructor for entity for inner class in Hibernate

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.

like image 224
xiaohan2012 Avatar asked Jul 24 '11 05:07

xiaohan2012


People also ask

Does entity class in Hibernate require no-arg constructor?

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.

Is org Hibernate InstantiationException no default constructor for entity?

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.

Why do we need a default constructor in entity class?

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.

What is the default constructor in Hibernate POJO?

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().


1 Answers

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(); 
like image 59
Bohemian Avatar answered Oct 01 '22 10:10

Bohemian