Reputation: 21405
I was going through the hibernate documentation and the document says that hibernate requires a no-arg constructor for all our persistent classes:
The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection. The constructor can be private, however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.
But when I created a sample program for testing by creating a POJO class without any no-arg constructor and by placing a constructor that takes parameters, I expected Hibernate will throw an exception but I was surprised to see that I was not getting exceptions.
Here is my POJO:
public class Event {
private Long id;
private String title;
public Event(String title) {}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Here is my program:
import org.hibernate.Session;
import java.util.*;
import org.hibernate.tutorial.domain.Event;
import org.hibernate.tutorial.util.HibernateUtil;
public class EventManager {
public static void main(String[] args) {
EventManager mgr = new EventManager();
mgr.createAndStoreEvent("My Event", new Date());
HibernateUtil.getSessionFactory().close();
}
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event("");
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
}
}
I have also configured hibernate configuration and mapping files. Now I can see that a new record is stored in my DB when I execute this program.
I am new to Hibernate, please help me in understanding the statement given in hibernate documentation as the document says we need a no-arg constructor. I am using Hibernate 3.x version.
Upvotes: 2
Views: 4225
Reputation: 115338
Try to read your event and you will see the exception.
The problem is not in saving object in database when object is already created by explicit call of the constructor. The problem is when hibernate reads record from DB and has to create corresponding object of mapped class. In this case it should create object. How can it do it without default constructor? Indeed there can be several constructor with arguments and it "does not know" which one to take.
So it does something like this:
Object obj = Class.forName(mappedClassName).newInstance();
pupulateProperties(obj);
newInstance()
requires no-args constructor.
Upvotes: 6
Reputation: 26094
You try this one then you will get the exception.
Event event = (Event)session.get(Event.class, eventId );
Add default constructor in your event class
public class Event {
public Event(){
}
}
Upvotes: 1