0

I'm using Hibernate to connect to my db and when I want to load data from the db I get null pointer exception at session. I don't know why? Everything looks good for me :< I have this class to read from db:

package bbstats.domain;

import bbstats.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EventManager extends HibernateUtil
{

    @Autowired
    SessionFactory sessionFactory;

    protected Class<DbUserData> clazz;

    public List<DbUserData> getAll()
    {
        return this.getCurrentSession().createCriteria(clazz).list();
    }

    protected final Session getCurrentSession()
    {
        return this.sessionFactory.getCurrentSession();
    }

    public static void main(String args[])
    {
        EventManager eventManager = new EventManager();
        System.out.println(eventManager.getAll());
    }
}

package bbstats.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateUtil extends HibernateDaoSupport
{
    private SessionFactory sessionFactory;

    @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }
}

package bbstats.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "Users")
public class DbUserData
{
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    @Column(name = "nick", nullable = false, length = 26)
    private String title;

    public DbUserData() {}

    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;
    }
}

and when I try to run it I get exception:

Exception in thread "main" java.lang.NullPointerException
    at bbstats.domain.EventManager.getCurrentSession(EventManager.java:25)

it's here:

protected final Session getCurrentSession()
{
    return this.sessionFactory.getCurrentSession();
}

why? How can I fix this?

Edit: I have file with this tags is it correct? I have no other files with tags

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:utils="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <!-- Hibernate session factory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" ref="sessionFactoryDomainToScan"/>

    </bean>

    <utils:list id="sessionFactoryDomainToScan">
        <value>bbstats.domain</value>
    </utils:list>


    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="clientProperties"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>


    <bean id="clientProperties"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations" value="/database.properties"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

    </bean>
</beans>

or should I add some other bean for my EventManager class? May it be that some beans are not needed?

dependencies:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.1.RELEASE</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.9.Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.3.RELEASE</version>
    </dependency>

now that exception: Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eventManager' defined in class path resource [hibernate.cfg.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hibernate.cfg.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition; Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hibernate.cfg.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider

vardius
  • 6,326
  • 8
  • 52
  • 97
  • I have updated my answer to show how you can add eventManager bean as part of your spring config file and then use it to retrieve the event manager instance – Ankit Bansal Mar 25 '13 at 16:44

3 Answers3

1

In order to inject the SessionFactory (thanks to the annotation @Autowired), the bean EventManager must be instanciated by the container (i.e. Spring) and not by yourself (as you do in your main method : EventManager eventManager = new EventManager();)

ben75
  • 29,217
  • 10
  • 88
  • 134
1

You should retrieve EventManager instance from spring context.

You can define eventManager as a bean in your file. You can define it as:

<bean id="eventManager" class="bbstats.domain.EventManager">
 <property name="sessionFactory" ref="sessionFactory"/>
</bean>

Let's say your spring config file name is springConfig.xml and eventManager is defined as bean, then you can use

ApplicationContext context = 
          new ClassPathXmlApplicationContext(new String[] {"springConfig.xml"});

        EventManager eventManager = (EventManager)context.getBean("eventManager");
Ankit Bansal
  • 4,962
  • 1
  • 23
  • 40
  • `Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0' defined in class path resource [hibernate.cfg.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/core/convert/support/PropertyTypeDescriptor` – vardius Mar 25 '13 at 16:48
  • this error means, you are having incompatible spring dependencies. PropertyTypeDescriptor has been removed from spring. Are you using a package manager? – Ankit Bansal Mar 25 '13 at 16:55
  • yes i'm useing maven i added to main question dependencies im useing – vardius Mar 25 '13 at 16:57
  • try to set all spring dependencies to the same release e.g. spring-orm to 3.2.1.RELEASE as well. It doesn't matter in this case, but you should also set hibernate-annotatiosn at 4.1.9-Final for consistency. Also, verify if your ide is using correct versions of all dependencies – Ankit Bansal Mar 25 '13 at 17:10
  • `4.1.9-Final` of hibernate-annotations not found – vardius Mar 25 '13 at 17:11
  • ok i left it on 2.5.6 and it went forward `java: cannot find symbol symbol: method setSessionFactory(org.hibernate.SessionFactory) location: class bbstats.util.HibernateUtil` `java: cannot access org.springframework.dao.support.DaoSupport class file for org.springframework.dao.support.DaoSupport not found` – vardius Mar 25 '13 at 17:14
  • Try adding spring-tx dependency in maven file: http://mvnrepository.com/artifact/org.springframework/spring-tx/3.2.1.RELEASE. That's what google says :) so might work. – Ankit Bansal Mar 25 '13 at 17:18
  • You are facing these issues because your dependencies are missing. You should put correct dependencies in maven(by googling for error) and put it in maven file. Make sure you pick the correct version. – Ankit Bansal Mar 25 '13 at 18:10
0

Delete this method:

 @Autowired
    public void anyMethodName(SessionFactory sessionFactory)
    {
        setSessionFactory(sessionFactory);
    }

and add @Autowired annotation to setSessionFactory method.

UPDATE

sea this links (here you can find solution):

  1. first
  2. second
  3. therd
Community
  • 1
  • 1
Aliaksei Bulhak
  • 6,078
  • 8
  • 45
  • 75