No default constructor for entity for inner class in Hibernate

xiaohan2012 picture xiaohan2012 · Jul 24, 2011 · Viewed 30.7k times · Source

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.

Answer

Bohemian picture Bohemian · Jul 24, 2011

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