2014-07-12 71 views
0

我是Hibernate的新手,當我嘗試向我的「RunEntity」數據庫中插入數據時,我正遇到空指針異常。Spring:Hibernate插入空指針異常

這裏是我的實體類

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

} 

我在我的應用程序類使用豆類設置數據庫

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 class

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) 
+0

分享錯誤堆棧跟蹤以便更好地理解 –

+1

我在猜測'Session'是'null'。 「@ Transactional」分界線將在哪裏創建交易?不相關,但是您正在使用引導,並且您正在配置大量缺省值(例如數據源和休眠屬性) –

+0

感謝您的迴應。我已經離開了本教程http://www.studytrails.com/frameworks/spring/spring-hibernate-session-factory-annotation.jsp並用@符號替換了xml文件,但本教程從未提及事務。我一直在環顧四周,但真的找不到一個包含該符號的好教程。你有什麼建議嗎? – user3073234

回答

0

的問題可能是您的currentSession可以爲空。你可以在代碼中調用插入方法嗎?

  1. 你應該叫服務對象,這由自動佈線或注入適當的插入方法

  2. 如果使用新創建的服務對象,你可以使用@Configurable用AspectJ一起編譯時織入注入對象