Spring:Hibernate插入空指针异常

时间:2014-07-12 21:28:23

标签: spring hibernate insert null javabeans

我是Hibernate的新手,当我尝试插入我的" RunEntity"时,我遇到了一个空指针异常。数据库中。

这是我的实体类

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;

@Entity
@Table(name = "TESTRUNS")
public class RunEntity {

private int ID;
private int testNumber;
private String testName;
private String environment;
private String source;
private String passOrFail;
private Timestamp date;
private byte[] resultFiles;


@Id
@Column(name = "ID")
@GeneratedValue
public int getID()
{
    return this.ID;
}
public void setID(int ID){this.ID = ID;}

@Column(name="TestNumber")
public int getTestNumber()
{
    return this.testNumber;
}
public void setTestNumber(int testNum){this.testNumber = testNum;}

@Column(name="TestName")
public String testName()
{
    return this.testName;
}
public void setTestName(String testName){this.testName = testName;}

@Column(name="Environment")
public String getEnvironment()
{
    return this.environment;
}
public void setEnvironment(String enviro){this.environment = enviro;}

@Column(name="Source")
public String getSource()
{
    return this.source;
}
public void setSource(String src){this.source = src;}

@Column(name="PassOrFail")
public String getPassOrFail()
{
    return this.passOrFail;
}
public void setPassOrFail(String pOrF){this.passOrFail = pOrF;}

@Column(name="Date")
public Timestamp getDate()
{
    return this.date;
}
public void setDate(Timestamp dates){this.date = dates;}

@Lob
@Column(name="ResultFiles")
public byte[] getResultFiles()
{
    return this.resultFiles;
}
public void setResultFiles(byte[] file){this.resultFiles = file;}

}

我使用bean在我的Applications类中设置数据库

import java.io.IOException;
 import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
public class Application {

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setPackagesToScan(new String[] { "web_application" });
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setAnnotatedClasses(RunEntity.class);
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}


@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

@Bean
public BasicDataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl("jdbc:hsqldb:mem://runDb");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    return dataSource;
}

@Bean
public DbUtil dbUtil()
{
    DbUtil dbUtil = new DbUtil();
    dbUtil.setDataSource(dataSource());
    dbUtil.initialize();
    return dbUtil;
}

public Properties hibernateProperties()
{
    Properties prop = new Properties();
    prop.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    return prop;
}

public static void main(String[] args) throws IOException {
    Object[] sources = { Application.class, NightlySchedule.class };
    SpringApplication.run(sources, args);
}
}

这是我的DAO课程

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

 @Repository
public class RunDao {

private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

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

public void insert(RunEntity run) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    session.save(run);
    session.getTransaction().commit();

}

public List<RunEntity> selectAll() {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(RunEntity.class);
    List<RunEntity> run = (List<RunEntity>) criteria.list();
    session.getTransaction().commit();
    return run;
}

}

这是我的dbUtil类

import java.sql.Connection;
import java.sql.SQLException;
 import java.sql.Statement;

 import javax.sql.DataSource;

 public class DbUtil {

private DataSource dataSource;

public DataSource getDataSource() {
    return dataSource;
}

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

public void initialize() {
    DataSource dataSource = getDataSource();
    try {
        Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        statement
                .executeUpdate("CREATE TABLE Run (ID INTEGER IDENTITY,TestNumber INTEGER NOT NULL, TestName varchar(50) NOT NULL, ENVIRONMENT VARCHAR(50) NOT NULL, Source VARCHAR(50), Date TIMESTAMP, RESULTFILES BLOB)");
        statement.close();
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

堆栈跟踪

java.lang.NullPointerException: null
at web_application.RunDao.insert(RunDao.java:26)
at web_application.IndexController.index(IndexController.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at     org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:695)

1 个答案:

答案 0 :(得分:0)

问题可能是您的currentSession可能为null。你能展示调用insert方法的代码吗?

  1. 您应该在服务对象上调用insert方法,该方法通过自动布线或

  2. 正确注入
  3. 如果使用new创建服务对象,则可以使用@Configurable和AspectJ编译时编织来注入对象