views:

29

answers:

1

Hi all, i have a simple JPanel bean in my projects, now i want to drag my panel bean class into my jframe.

My panel bean class is like this:

public class BeanPanel extends javax.swing.JPanel {

/** Creates new form BeanPanel */
public BeanPanel () {
    initComponents();
    Session session=HibernateUtil.getSessionFactory().openSession();
}

This code seem to break the bean:

Session session=HibernateUtil.getSessionFactory().openSession();

When i try to drag the class into my JFrame bean i had this error message:

This component cannot be instantiated. Please make sure it is a JavaBeans Component

If i comment it all works fine. What is the reason of this?

Thanks.

+1  A: 

Don't do expensive work (like opening a session) in the constructor. At best use only assignments in constructor. In your case when placing the component, NetBeans is calling its constructor. Which can't connect, because probably the appropriate configurations aren't loaded, or because the classpath is correct, or whatever.

create a getter and setter for session, and use lazy initialization in the getter:

public Session getSession() {
   if (session == null) {
       HibernateUtils.getSessionFactory().openSession();
   }
}

That said, I think you may have problems with session handling. Perhaps you can take a look at the getCurrentSession() method of SessionFactory.

Another thing - don't mix database access and UI. Move the handling of data outside your Panels.

Bozho
Thank you very much, in fact i read messages.log and i noticed i have an hibernatehexcpetion to read hibernate.cfg.xml.So, i have to make a class to handle session and data saving/selecting? This panel is a simple panel with form to insert data in my db.
blow
Another question, is better to open session one time and after retrieve the session with getCurrentSession() without close it?
blow
for that read the hibernate's documentation, and then ask another question here, if you do not understand some parts of it.
Bozho
While I wouldn't get the session in the constructor, opening a session is not really expensive.
Pascal Thivent
yes, it's not, but that's an "implementation detail". :)
Bozho