Hibernate 4 + Spring + getHibernateTemplate()。getSessionFactory()。getCurrentSession()

时间:2014-12-31 01:07:07

标签: java spring hibernate

想要使用Spring自动使用Hibernate 4会话 我也喜欢扩展DAO,因为没有为许多实体创建许多DAO 但是有问题:

SessionDAO.java

public abstract class SessionDAO extends HibernateDaoSupport{

    public void startSession() {

        getSession().beginTransaction();
    }

    public void closeSession() {
        getSession().getTransaction().commit();
    }

    public void addObject() {
        startSession();
        getSession().save(this);
        closeSession();
    }

    public Session getSession()
    {
        return getHibernateTemplate().getSessionFactory().getCurrentSession();

    }
}

Values.java

@Entity
@Table
public class Values extends SessionDAO {
private int valuesId;
private double amount;
private Date date;
//...getters, setters, etc
}

调度-servlet.xml中

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>entity.Crypto</value>
            <value>entity.Values</value>
        </list>
    </property>
      <property name="hibernateProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
         </props>
      </property>

   </bean>

   <bean id="dataSource"
    class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
      <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
      <property name="url" value="jdbc:oracle:thin:@my.****.us-east-1.rds.amazonaws.com:1521:ORCL" />
      <property name="username" value="****" />
      <property name="password" value="****" />
   </bean>

   <bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
   </bean>

   <bean id="persistenceExceptionTranslationPostProcessor"
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

启动服务器时,收到:

INFO: HHH000206: hibernate.properties not found

尝试加载页面接收时:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException

在线

return getHibernateTemplate().getSessionFactory().getCurrentSession();

出了什么问题?

1 个答案:

答案 0 :(得分:0)

不能通过扩展 HibernateDaoSupport 来获取会话,只需在 DAO 中注入 SessionFactory

private HibernateTemplate hibernateTemplate;

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