Hibernate空指针异常

时间:2015-03-04 14:42:51

标签: spring hibernate jsp spring-mvc sessionfactory

我在DAO中的以下行收到空指针异常:

Session session = sessionFactory.getCurrentSession();

我不完全确定为什么我使用session / sessionFactory实例向控制台打印正确的值但是当我尝试在jsp中输出相同的值时,我得到空指针异常。

我的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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.sga.app.dao"></context:component-scan>
    <jee:jndi-lookup jndi-name="jdbc/springSgaDb" id="dataSource"
        expected-type="javax.sql.DataSource">
    </jee:jndi-lookup>

        <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
        </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.sga.app.beans</value>
                <value>com.sga.app.dao</value>
            </list>
        </property>

        <property name="annotatedClasses">
            <array>
                <value>com.sga.app.dao.DisplayStatsDAO</value>
            </array>
        </property>
        <!-- -->

    </bean>

    <bean id="exceptionTranslator"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
    </bean>
    <tx:annotation-driven />
    </beans>

我的道:

package com.sga.app.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sga.app.beans.UserBean;

@SuppressWarnings("unchecked")
@Component("displayStatsDAO")
@Transactional
@Repository
@Configuration
public class DisplayStatsDAO implements Serializable {

    private static final long serialVersionUID = 1L;

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Bean
    public DisplayStatsDAO displayStatsDAO() {
        return new DisplayStatsDAO();
    }

    public DisplayStatsDAO() {

    }

    public String getLoggedInUserName(String username) {
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        String userLoggedIn = authentication.getName();
        return userLoggedIn;
    }

    @Transactional
    public ArrayList<Object> showMyStats() {

        @SuppressWarnings("rawtypes")
        ArrayList result = new ArrayList();
        try {

            /*
             * SessionFactory factory = (SessionFactory) new
             * org.hibernate.cfg.Configuration
             * ().configure().buildSessionFactory(); Session sesh =
             * factory.openSession(); sesh.beginTransaction();
             */

            Session session = sessionFactory.getCurrentSession();
            Authentication authentication =   SecurityContextHolder.getContext()
                    .getAuthentication();
            String userLoggedIn = authentication.getName();
            System.out.println(userLoggedIn);
            session.beginTransaction();
            Criteria criteria = session.createCriteria(UserBean.class);
            criteria.add(Restrictions.like("username", userLoggedIn));
            List<UserBean> user = (List<UserBean>) criteria.list();
            // session.getTransaction().commit();
            for (UserBean userDetails : user) {
                System.out.println("SHOW LOGGED-IN USER");
                System.out.println("Username: " + userDetails.getUsername());
                result.add(userDetails.getUsername());
                System.out.println("Name: " + userDetails.getForename() + ""
                        + userDetails.getSurname());
                result.add(userDetails.getForename());
                result.add(userDetails.getSurname());
                System.out.println("Homeclub: " + userDetails.getHomeclub());
                result.add(userDetails.getHomeclub());
                System.out.println("GIR: " + userDetails.getGir());
                result.add(userDetails.getGir());
                System.out
                        .println("Fairways: " + userDetails.getFairways_hit());
                result.add(userDetails.getFairways_hit());
                System.out.println("Putts: " + userDetails.getPutts());
                result.add(userDetails.getPutts());
                System.out.println("Score average: "
                        + userDetails.getScore_avg());
                result.add(userDetails.getScore_avg());
                System.out
                        .println("Sand saves: " + userDetails.getSand_saves());
                result.add(userDetails.getSand_saves());
                System.out.println();
                System.out.println(result.get(0).toString());
                System.out.println(result.get(3).toString());               
                return result;
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return result;
    }  
}

我的jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@page import="com.sga.app.dao.DisplayStatsDAO" %>
<%@page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="${pageContext.request.contextPath}/static/css/main.css"
    rel="stylesheet" type="text/css">
<title>SGA-user stats</title>
</head>
<body>
    <!-- Logout option -->
    <div id="logoutOptionDiv" align="right">
        <a id="logoutOption" style="color: blue;"
            href='<c:url value="/j_spring_security_logout"></c:url>'>Logout</a>
    </div>
    <br />
    <!-- Page nav -->
    <div>
        <a style="font-weight: bold;"
            href="${pageContext.request.contextPath}/menu">Main menu</a> <a
            style="font-weight: bold; margin-left: 15px;"
            href="${pageContext.request.contextPath}/roundanalysis">Round
            analysis</a>
    </div>
    <br />
    <br />
    <h2 class="displayStatsLeaderboardHeader">Your stats</h2>
    <table class="displayStatsTable" border="1">
        <tr>
            <td>Username</td>
            <td>Forename</td>
            <td>Surname</td>
            <td>Average Score</td>
            <td>GIR (%)</td>
            <td>Fairways hit (%)</td>
            <td>Sand saves (%)</td>
            <td>Putts per round</td>
        </tr>
    <%DisplayStatsDAO stats = new DisplayStatsDAO();%>
        <tr>
            <td class="displayStatsTableData"><%stats.showMyStats().get(0).
              toString();%>
            </td>
            <td class="displayStatsTableData">${row.surname}</td>
            <td class="displayStatsTableData">${row.average_score}</td>
            <td class="displayStatsTableData">${row.gir}</td>
            <td class="displayStatsTableData">${row.fairways_hit}</td>
            <td class="displayStatsTableData">${row.sand_saves}</td>
            <td class="displayStatsTableData">${row.putts}</td>
        </tr>
    </table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

当你在jsp中编写new DisplayStatsDAO()时,它会在Spring容器的上下文之外进行初始化。 Spring没有办法将Session注入DAO。