-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Hibernate Spring Dao error "java.lang.NullPointerExcept
PostPosted: Wed Nov 19, 2008 9:04 pm 
Newbie

Joined: Tue Jun 10, 2008 4:40 am
Posts: 13
Hi, all

I have tried use hibernate with spring, but until now i not yet success
Event i tried to save data get error "java.lang.NullPointerException"
this below my code

Thanks a lot for your help


hibernate.cfg.xml
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
   
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- Enable Hibernate’s automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="mst.hrd.hibernate.model.annotation.GroupUser"/>
</session-factory>
</hibernate-configuration>


spring.ctx.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
   
    <context:component-scan base-package="mst.hrd.hibernate" />
    <tx:annotation-driven transaction-manager="txManager" />
   
   <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource"
         p:driverClassName="${hibernate.connection.driver_class}"
         p:url="${hibernate.connection.url}"
         p:username="${hibernate.connection.username}"
         p:password="${hibernate.connection.password}" />
   
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
          p:dataSource-ref="dataSource">
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                          ${hibernate.dialect}
                </prop>
                <prop key="hibernate.show_sql">
                          ${hibernate.show_sql}
                </prop>
                <prop key="hibernate.generate_statistics">
                          ${hibernate.show_statistics}
                </prop>
            </props>
        </property>
    </bean>
   
    <bean id="txManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager"
                p:sessionFactory-ref="sessionFactory" />
               
            </beans>


GroupUser.java
Code:
package mst.hrd.hibernate.model.annotation;

import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

/**
*
* @author user
*/
@Entity
@Table(name="t_groupuser")

public class GroupUser implements java.io.Serializable{

    @Transient
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="ID_GROUP")
    private int idGroup;
   
    @Column(name="DESCRIPTION",nullable=false,unique=true,length=25)
    private String description;
   
    @Column(name="ACCESS",nullable=false,length=500)
    private String access;
   
    @Column(name = "PROG_NAME", nullable = false, length = 15)
    private String progName;
   
   
    @OneToMany(mappedBy="groupUser")
    private List<User> user = new ArrayList<User>();
   
    public PropertyChangeSupport getChangeSupport() {
        return changeSupport;
    }

    public void setChangeSupport(PropertyChangeSupport changeSupport) {
        this.changeSupport = changeSupport;
    }

    public int getIdGroup() {
        return idGroup;
    }

    public void setIdGroup(int idGroup) {
        this.idGroup = idGroup;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAccess() {
        return access;
    }

    public void setAccess(String access) {
        this.access = access;
    }

    public String getProgName() {
        return progName;
    }

    public void setProgName(String progName) {
        this.progName = progName;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

   
}




GroupUserDao.java
Code:
package mst.hrd.hibernate.dao;

import java.util.List;
import mst.hrd.hibernate.model.annotation.GroupUser;

/**
*
* @author user
*/
public interface GroupUserDao {
 
   public void save(GroupUser groupUser);

   public void delete(GroupUser groupUser);

   public GroupUser getGroupUser(int id);

   public List<GroupUser> getGroupUser();
}



GroupUserHql.java
Code:
package mst.hrd.hibernate.dao.hql;

import java.util.List;
import mst.hrd.hibernate.dao.GroupUserDao;
import mst.hrd.hibernate.model.annotation.GroupUser;
import mst.hrd.hibernate.properties.HibernateConnection;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
*
* @author user
*/
@Repository("groupUserDaoHql")
public class GroupUserHql implements GroupUserDao{

private SessionFactory sessionFactory;

@Autowired
   public void setSessionFactory(SessionFactory sessionFactory) {
   this.sessionFactory = sessionFactory;
  }
   
   
    public void save(GroupUser groupUser) {
        HibernateConnection.getHibernateConnection();
        HibernateConnection.sf.getCurrentSession().saveOrUpdate(groupUser);
    }

    public void delete(GroupUser groupUser) {
        sessionFactory.getCurrentSession().delete(groupUser);
    }

    public GroupUser getGroupUser(int id) {
    GroupUser groupUser =
                (GroupUser) sessionFactory.getCurrentSession()
                .createQuery("from GroupUser g left join fetch g.user where g.id=?")
                .setParameter(0, id).uniqueResult();
        return groupUser;
    }

    public List<GroupUser> getGroupUser() {
    List<GroupUser> groupUser= sessionFactory.getCurrentSession()
                .createQuery("from GroupUser order by id").list();
    return groupUser;
    }


}



UserService.java
Code:
package mst.hrd.hibernate.dao.services;

import java.util.List;
import mst.hrd.hibernate.model.annotation.GroupUser;
import mst.hrd.hibernate.model.annotation.User;

/**
*
* @author user
*/
public interface UserService {

public void save(GroupUser groupUser);
public void delete(GroupUser groupUser);
public GroupUser getGroupUser(int id);
public List<GroupUser> getGroupUser();

}



UserServiceImpl.java
Code:
package mst.hrd.hibernate.dao.services.impl;

import java.util.List;
import mst.hrd.hibernate.dao.GroupUserDao;
import mst.hrd.hibernate.dao.UserDao;
import mst.hrd.hibernate.dao.hql.GroupUserHql;
import mst.hrd.hibernate.dao.hql.UserDaoHql;
import mst.hrd.hibernate.dao.services.UserService;
import mst.hrd.hibernate.model.annotation.GroupUser;
import mst.hrd.hibernate.model.annotation.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
*
* @author user
*/
@Repository("userService")
@Transactional(readOnly=true)
public class UserServiceImpl implements UserService{
   
private GroupUserDao groupUserDao;
private UserDao userDao;


    @Autowired
    public void setGroupUserDao(@Qualifier("groupUserHql")GroupUserHql groupUserDao) {
    this.groupUserDao=groupUserDao;   
    }

    @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
    public void save(GroupUser groupUser) {
    groupUserDao.save(groupUser);
    }

   
    @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
    public void delete(GroupUser groupUser) {
    groupUserDao.delete(groupUser);
    }

   
    public GroupUser getGroupUser(int id) {
       return groupUserDao.getGroupUser(id);
    }

   
     
    public List<GroupUser> getGroupUser() {
      return groupUserDao.getGroupUser();
    }

   
}



HibernateConnection.java
Code:
package mst.hrd.hibernate.properties;

import mst.common.Variable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
*
* @author root
*/
public class HibernateConnection {
public static SessionFactory sf;
public static Session session;

private static Variable var = new Variable();

public static void getHibernateConnection(){
      try {
               sf = HibernateUtilMySQL.getSessionFactory();
               session = sf.getCurrentSession();
          }catch(Exception e){
                                      e.printStackTrace();
                                     }
      
}

public static void closeHibernateConnection(){
     if (session!=null){try {session.close();} catch(Exception e){}finally{session.close();}}
     if (sf!=null)     {try {sf.close();}      catch(Exception e){}finally{sf.close();}}
}

}


HibernateUtilMySQL.java
Code:
package mst.hrd.hibernate.properties;
import mst.common.Variable;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtilMySQL {
private static Variable var = new Variable();   
   
private static final SessionFactory sessionFactory;
   static {
      try {
                            String host=var.host;
                            String db=var.dbGlobal;
                            String user=var.getUserMst();
                            String pwd=var.getPwdMst();
                       
           // Create the SessionFactory from hibernate.cfg.xml
                              sessionFactory = new AnnotationConfiguration()
                                .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
                                .setProperty("hibernate.connection.url", "jdbc:mysql://"+host+ "/"+db+"")
                                .setProperty("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect")
                                .setProperty("hibernate.connection.username", user)
                                .setProperty("hibernate.connection.password", pwd).configure().buildSessionFactory();
          } catch (Throwable ex) {
                         // Make sure you log the exception, as it might be swallowed
                         System.err.println("Initial SessionFactory creation failed." + ex);
                         throw new ExceptionInInitializerError(ex);
                             }
         }
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }




MDIMainMenu.java
Code:
public class MDIMainMenu extends javax.swing.JFrame {
   
private static ApplicationContext applicationContext;

...
...

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
   
    try {   
       
                     HibernateConnection.getHibernateConnection();
                     applicationContext = new ClassPathXmlApplicationContext("spring.ctx.xml");
       
       }catch(Exception e){
                                   
                                    }
   
}                                 



public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

     public static  UserService getUserService(){
     
  //error here
       // at mst.hrd.main.MDIMainMenu.getUserService(MDIMainMenu.java:834)
        return (UserService)applicationContext.getBean("userService");
 
  }
 


JDGroupUsers.java
Code:
public class JDGroupUsers extends javax.swing.JDialog {
   
    public JDGroupUsers(ShowFormMenu aThis, boolean b) {
        initComponents();
        setVisible(true);
    }


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try{
    GroupUser selectedGroup = new GroupUser();
    selectedGroup.setDescription(txtDescription.getText());

   //error here
    // at mst.hrd.view.ui.system.JDGroupUsers.jButton1ActionPerformed(JDGroupUsers.java:86)
    MDIMainMenu.getUserService().save(selectedGroup);
 
  }catch(Exception e){
                                e.printStackTrace();
                              }
    }                                       
   


error message
Code:
java.lang.NullPointerException
        at mst.hrd.main.MDIMainMenu.getUserService(MDIMainMenu.java:834)
        at mst.hrd.view.ui.system.JDGroupUsers.jButton1ActionPerformed(JDGroupUsers.java:86)
        at mst.hrd.view.ui.system.JDGroupUsers.access$000(JDGroupUsers.java:21)
        at mst.hrd.view.ui.system.JDGroupUsers$1.actionPerformed(JDGroupUsers.java:51)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6038)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
        at java.awt.Component.processEvent(Component.java:5803)
        at java.awt.Container.processEvent(Container.java:2058)
        at java.awt.Component.dispatchEventImpl(Component.java:4410)
        at java.awt.Container.dispatchEventImpl(Container.java:2116)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
        at java.awt.Container.dispatchEventImpl(Container.java:2102)
        at java.awt.Window.dispatchEventImpl(Window.java:2429)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
        at java.awt.Dialog$1.run(Dialog.java:1039)
        at java.awt.Dialog$3.run(Dialog.java:1091)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.awt.Dialog.show(Dialog.java:1089)
        at java.awt.Component.show(Component.java:1419)
        at java.awt.Component.setVisible(Component.java:1372)
        at java.awt.Window.setVisible(Window.java:801)
        at java.awt.Dialog.setVisible(Dialog.java:979)
        at mst.hrd.view.ui.system.JDGroupUsers.<init>(JDGroupUsers.java:27)
        at mst.hrd.main.showmenu.ShowFormMenu.showJDGroupUsers(ShowFormMenu.java:49)
        at mst.hrd.main.MDIMainMenu.mniGroupUsersActionPerformed(MDIMainMenu.java:809)
        at mst.hrd.main.MDIMainMenu.access$1600(MDIMainMenu.java:45)
        at mst.hrd.main.MDIMainMenu$16.actionPerformed(MDIMainMenu.java:361)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
        at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1216)
        at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1257)
        at java.awt.Component.processMouseEvent(Component.java:6038)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
        at java.awt.Component.processEvent(Component.java:5803)
        at java.awt.Container.processEvent(Container.java:2058)
        at java.awt.Component.dispatchEventImpl(Component.java:4410)
        at java.awt.Container.dispatchEventImpl(Container.java:2116)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
        at java.awt.Container.dispatchEventImpl(Container.java:2102)
        at java.awt.Window.dispatchEventImpl(Window.java:2429)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Nov 19, 2008 11:37 pm 
Regular
Regular

Joined: Tue Sep 26, 2006 11:37 am
Posts: 115
Location: Sacramento, CA
It seems that formWindowOpened() is called later than you expect and applicationContext is not initialized properly.

I think it is better to hide the spring dependencies in some global class that is fully initialized after the application is up instead of putting static members in your view/menu classes and having to worry about all the initialization throughout your code.

Somehow related: I do not know how you generated your application, I really like Netbeans for kicking of Swing projects.


Good luck,

Marius


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.