繁体   English   中英

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

[英]Hibernate 4 + Spring + getHibernateTemplate().getSessionFactory().getCurrentSession()

想使用 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();

    }
}

值.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();

怎么了?

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

private HibernateTemplate hibernateTemplate;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM