简体   繁体   English

Hibernate 4 - 调用DAO并初始化sessionFactory bean

[英]Hibernate 4 - Calling DAO and Initializing sessionFactory bean

I'm in the middle of updating my old program to Spring 3.2 and Hibernate 4 and am running into a couple of difficulties with sessionFactory (I was using hibernateTemplate before). 我正在将我的旧程序更新到Spring 3.2和Hibernate 4,并且遇到了一些与sessionFactory有关的困难(之前我正在使用hibernateTemplate)。

  1. I don't think the way I am accessing the DAO is the best way to do it, but I don't see how else to make it work. 我不认为我访问DAO的方式是最好的方法,但我不知道如何让它工作。 If I do a simple creation of the DAO object (CSSDAO d = new CSSDAOImpl();), the sessionFactory is always null. 如果我简单地创建DAO对象(CSSDAO d = new CSSDAOImpl();),则sessionFactory始终为null。 If I have it the way I do below, it works. 如果我按照下面的方式使用它,它就可以了。 What is the proper way to call the DAO methods? 调用DAO方法的正确方法是什么? (please ignore the MVC portion of the controller, I know that needs its own work) (请忽略控制器的MVC部分,我知道需要自己的工作)

  2. I'm opening a new session in every method in the DAO. 我正在DAO中的每个方法中打开一个新会话。 I know this isn't correct, as I should be getting the current session. 我知道这不正确,因为我应该参加当前的会议。 But everytime I try to get the current session, it says one doesn't exist. 但每当我试图获得当前会话时,它就说不存在。 How does the session get "initialized" the first time? 会话如何在第一次“初始化”? I thought it would inject it based on the XML configuration, but that doesn't seem to be doing anything here. 我认为它会基于XML配置注入它,但这似乎没有在这里做任何事情。 Any thoughts? 有什么想法吗?

hibernate-cfg.xml 冬眠-cfg.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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

    <bean id="myDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"></property>
        <property name="url" value="jdbc:derby:C:\Users\Steven\MyDB"></property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="packagesToScan" value="net.form" />
        <property name="dataSource" ref="myDataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>net.form.StyleChooser</value>
            </list>
        </property>
    </bean>

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

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="CSSDAO" class="dao.CSSDAOImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

DAO: DAO:

package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import net.form.StyleChooser;

public class CSSDAOImpl implements CSSDAO {

    private SessionFactory sessionFactory;

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

    @Transactional
    public List selectAllCSS() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        List l = session.createCriteria(StyleChooser.class).list();
        session.flush();
        tx.commit();
        return l;
    }

    @Transactional
    public StyleChooser selectCSSById(Integer ID) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        StyleChooser sc = (StyleChooser) session.get(StyleChooser.class, ID);
        session.flush();
        tx.commit();        
        return sc;
    }

    @Transactional
    public Integer insertCSS(StyleChooser insertCSS) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Integer id = (Integer) session.save(insertCSS);
        session.flush();
        tx.commit();
        return id;
    }

    @Transactional
    public void deleteCSS(Integer CSSId) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        StyleChooser sc = (StyleChooser) session.get(StyleChooser.class, CSSId);
        session.delete(sc);
        session.flush();
        tx.commit();
    }

    @Transactional
    public void updateCSS(StyleChooser cssWithNewValues) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.update(cssWithNewValues);
        session.flush();
        tx.commit();        
    }
}

Accessing DAO... 访问DAO ...

package net.controllers;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.form.StyleChooser;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import dao.CSSDAOImpl;

@Controller
@RequestMapping("/stylechoosertable.html")
public class IndexController extends MultiActionController {

    Resource resource = new FileSystemResource(
            "C:/Users/Steven/Desktop/Programming/workspace/CSSGeneratorHibernate4/WebContent/WEB-INF/hibernate.cfg.xml");
    BeanFactory beanFactory = new XmlBeanFactory(resource);
    CSSDAOImpl dao = (CSSDAOImpl) beanFactory.getBean("CSSDAO");

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showIndex(HttpServletRequest request) throws Exception {
        List<StyleChooser> styleChooser = dao.selectAllCSS();
        return new ModelAndView("stylechoosertable", "styleChooser", styleChooser);
    }
}

Few observation: 几点观察:

  1. In your retrieve methods, transaction shouldn't be used ie they should be non-transactional. 在检索方法中,不应使用事务,即它们应该是非事务性的。

  2. Add <tx:annotation-driven transaction-manager="transactionManager"/> in your configuration to recognize the transactional annotations. 在配置中添加<tx:annotation-driven transaction-manager="transactionManager"/>以识别事务注释。

  3. If you use @Transactional annotation then don't need to use programmatic transactions. 如果使用@Transactional注释,则不需要使用编程事务。 Add the propagation attribute in the @Transactional annotation as @Transactional(propagation=Propagation.REQUIRED) and leave the transaction management to Hibernate. @Transactional注释中的propagation属性添加为@Transactional(propagation=Propagation.REQUIRED) ,并将事务管理保留给Hibernate。

  4. For first time you need to open the session and if not closed you may use the same session next time. 您第一次需要打开会话,如果没有关闭,您可能会在下次使用相同的会话。 For getting the session , better to use an utility method as below: 要获得session ,最好使用如下的实用方法:

     private Session getSession(SessionFactory sessionFactory){ Session session = null; try{ session = sessionFactory.getCurrentSession(); }catch(HibernateException hex){ hex.printStackTrace(); } if(session == null && !session.isClosed()){ session = sessionFactory.openSession(); } } 

This way, you will get the session if available and open otherwise open a new session. 这样,您将获得会话(如果可用)并打开,否则打开新会话。

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

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