1

I have expected Hibernate to be able to instantiate class using protected no-args constructor, however, we got: org.hibernate.HibernateException: Could not instantiate resultclass: com.xxx.Installment.

After changing from:

@VisibleForHibernate
protected Installment() {
}

to:

@VisibleForHibernate
public Installment() {
}

the problem has been fixed. Hibernate version we use: 3.6.10.Final.

Are there any rules as to when the no-args constructor must be public as opposed to protected in order for Hibernate to work?

OlgaMaciaszek
  • 3,662
  • 1
  • 28
  • 32

1 Answers1

1

From the reference

https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/persistent-classes.html#persistent-classes-pojo-constructor

All persistent classes must have a default constructor (which can be non-public) so that Hibernate can instantiate them using Constructor.newInstance(). It is recommended that you have a default constructor with at least package visibility for runtime proxy generation in Hibernate.

Since Hibernate user reflection, Hibernate requires that constructor should be public or it should have package level visibility.

Deendayal Garg
  • 5,030
  • 2
  • 19
  • 33
  • But they write it should be at least package visibility and `protected` is higher. It also provides package level, as specified here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – OlgaMaciaszek Sep 15 '16 at 10:29
  • Protected constructor can only be used with in the package, if someone tries to initiate the class with protector constructor in other package then it wont let it initiate. Try this with an example. – Deendayal Garg Sep 15 '16 at 10:40
  • @DeendayalGarg that's wrong. Although you cannot call a protected constructor from outside a classe's hierarchy, still any subclass B of a class A, belonging to *any* package can call a protected constructor of A. – Kostas Filios Jul 28 '18 at 11:18