2

In xml approach of hibernate when we create hibernate SessionFactory object using

private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

then it will call default constructor of persistance class 3 times it means for creating Session factory object it needs default constructor of persistance class but if I am removing default constructor from my class and only argument constructor is there in this case JVM not provide default constructor then how session factory object is created ?

Sumit
  • 109
  • 1
  • 9

3 Answers3

3

Actually, you can instantiate classes which have no 0-args constructor; you can get a list of a class' constructors,pick one and invoke it with different parameters. While this is possible, and I checked it would work and wouldn't be problematic, you'll have to agree that is pretty weird.

Constructing objects the way Hibernate does (I believe it invokes the 0-arg constructor and then it probably modifies the instance's fields directly via Reflection. Perhaps it knows how to call setters) goes a little bit against how is an object supposed to be constructed in Java invoke the constructor with the appropriate parameters so that the new object is the object you want.

0

Hibernate tries to create a bean and it does it via reflection. It does the object creation by calling the no-arg constructor, and then using the setter methods to set the properties. You can't use a bean that doesn't have a no-arg constructor.

If you don't have a default constructor you should get an exception

org.hibernate.InstantiationException: No default constructor for entity: <ClassName>

More reading

Community
  • 1
  • 1
Andy Dufresne
  • 6,022
  • 7
  • 63
  • 113
  • Andy, thank you for your response but I don' have any default constructor in my pojo class and it still able to save the data without any error so what is the use of default constructor . – Sumit Dec 25 '14 at 06:28
  • Hibernate calls that default constructor during object creation – Andy Dufresne Dec 25 '14 at 06:43
0

Hibernate by default use no-argument constructor to instantiated the pojo class object.

But if Default constructor is not there in pojo class then it can use argument ed constructor if there are multiple argument ed constructors are there then it will throw error

org.hibernate.InstantiationException: No default constructor for entity: <ClassName>
Pang
  • 9,564
  • 146
  • 81
  • 122
Sumit
  • 109
  • 1
  • 9