4

Please forgive me, I'm fairly new to this and pretty well clueless. I'm trying to create a pure console app inside an already working spring web project, for testing purposes:

Here is the main class:

@Component
@Transactional
public class Test {

    @Autowired
    StudentDAO dao;
    public static void main(final String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
        Test test = ctx.getBean(Test.class);
        test.print();
    }

    private void print() {
        Student s = dao.getByID(1);
        System.out.println(s.getFirstname());
    }
}

StudentDAO:

public interface StudentDAO {
    public void add(Student s);
    public void delete(Integer id);
    public ArrayList<Student> getAll();
    public Student getByID(Integer id);
    public Map<Integer, String> getMajors();
}

StudentDAOImp:

@Service
public class StudentDAOImp implements StudentDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void add(Student s) {
        sessionFactory.getCurrentSession().merge(s);
    }

    @Override
    public void delete(Integer id) {
        Student s = getByID(id);
        sessionFactory.getCurrentSession().delete(s);
    }

    @Override
    public ArrayList<Student> getAll() {
        Query query = sessionFactory.getCurrentSession().createQuery("from Student");
        List<?> l = query.list(); // query returns a raw list. 
        ArrayList<Student> studentlist = new ArrayList<Student>();
        for(Object o : l) {  // objects in list must be cast individually
            Student s = (Student) o;
            studentlist.add(s);
        }
        return studentlist;
    }

    @Override
    public Student getByID(Integer id) {
        return (Student) sessionFactory.getCurrentSession().get(Student.class, id);
    }

    @Override
    public Map<Integer, String> getMajors() {
        Query query = sessionFactory.getCurrentSession().createQuery("from Major");
        List<?> l = query.list();    // query returns a raw list. 
        Map<Integer, String> majorlist = new LinkedHashMap<Integer, String>();
        for(Object o : l) {     // objects in list must be cast individually
            Major m = (Major) o;
            majorlist.put(m.getMajorid(), m.getMajor());
        }
        return majorlist;
     }
}

spring-config.xml:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <tx:annotation-driven />

    <context:annotation-config/>
    <context:component-scan base-package="com.eaglecrk.springtraining.dao" />
    <context:component-scan base-package="com.eaglecrk.springtraining.test" />

      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
    <property name="url" value="jdbc:sqlserver://localhost\\SQLEXPRESS:1433;integratedSecurity=true;DatabaseName=StudentDB;" />
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
      <props>
        <prop 
         key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
    <property name="packagesToScan">
        <list>
            <value>com.eaglecrk.springtraining.thingies</value>
            <value>com.eaglecrk.springtraining.test</value>
        </list>
    </property>
  </bean>

  <bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory">
  </bean>
</beans>

And the actual error:

Exception in thread "main" java.lang.NullPointerException
    at com.eaglecrk.springtraining.test.Test.print(Test.java:26)
    at com.eaglecrk.springtraining.test.Test.main(Test.java:22)

The log output:

Jun 13, 2014 1:59:17 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@33dd66fd: startup date [Fri Jun 13 13:59:17 CDT 2014]; root of context hierarchy
Jun 13, 2014 1:59:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Jun 13, 2014 1:59:17 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
Jun 13, 2014 1:59:18 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 13, 2014 1:59:18 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Jun 13, 2014 1:59:18 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 13, 2014 1:59:18 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 13, 2014 1:59:18 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Jun 13, 2014 1:59:18 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jun 13, 2014 1:59:18 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jun 13, 2014 1:59:18 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@ed2bc5a] of Hibernate SessionFactory for HibernateTransactionManager
Exception in thread "main" java.lang.NullPointerException
    at com.eaglecrk.springtraining.test.Test.print(Test.java:28)
    at com.eaglecrk.springtraining.test.Test.main(Test.java:23)
toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
austior
  • 123
  • 2
  • 11

2 Answers2

0

you have to configure the Test class in spring -config .xml in bean tag as you annotated the Test.java as @component

Gowtham
  • 1
  • 1
  • I tried adding the following to my spring-config.xml: and I get the same error. It was my understanding that I didn't need to do this because of the – austior Jun 23 '14 at 14:29
  • can you please change @ service to @ repository – Gowtham Jun 23 '14 at 14:37
  • can you please place the @Transactional in StudentDAOImp class , place the annotation your are using , for example your are calling get method , so annotate getByid(id) as @Transactional(readOnly=true) public Student getByID(Integer id) { return (Student) sessionFactory.getCurrentSession().get(Student.class, id); } – Gowtham Jun 24 '14 at 06:08
  • The problem here is that dao impl is not injected into. I have prepared a simple test with trivial beans and that works as expected. If there was any configuration problem context boot-up would fail. So either your dao bean is not found or there is some bug in spring. I will try to reconstruct you problem. Which version of spring, hibernate are you using ? – bmichalik Jun 24 '14 at 07:51
0

Are you sure that the NPE is not caused by System.out.println(s.getFirstname()); thus you do not have the object in the database? If there was bean wiring problem it would result in context boot-up fail (provided your version of spring ioc does not have some strange bug).

bmichalik
  • 196
  • 6