No default constructor for entity for inner class in Hibernate
Asked Answered
G

3

36

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.

Gao answered 24/7, 2011 at 5:41 Comment(1)
It would help a lot if you included the hibernate warning ID "HHH000182" in this posting. The static thing fixed stuff for me, but finding this answer was hard!Occlusive
V
46

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();
V2 answered 24/7, 2011 at 5:46 Comment(0)
B
10

I always add an empty protected constructor to the class to solve this issue like so:

protected Classname(){}

In your case it would look like this:

protected Id(){}
Betray answered 15/3, 2012 at 14:38 Comment(1)
How does this solve the issue? You still need to have a static class.Sarawak
S
0

If class is non static it will require outer class instance to exist. So, I think, generated constructor in this case will have implicit parameter for outer class.


Update

As I expected:

$ javap -classpath . Supply\$Id
Compiled from "Supply.java"
class Supply$Id extends java.lang.Object{
    final Supply this$0;
    Supply$Id(Supply);
}
Scevour answered 24/7, 2011 at 5:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.