OpenSessionInView的问题

时间:2012-12-10 12:02:20

标签: spring hibernate lazy-loading open-session-in-view

我已经实现了Spring / Hibernate的OpenSessionInView模式以进行延迟加载。我面临着“没有Sessoon”或“2次或更多次会议”的问题。让我知道如果我错过了任何步骤:

以下是详细代码片段:

WEB.XML

      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
      </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

      <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
          <param-name>singleSession</param-name>
          <param-value>false</param-value>
        </init-param>
        <init-param>
          <param-name>flushModeName</param-name>
          <param-value>FLUSH_AUTO</param-value>
        </init-param>
        <init-param>
          <param-name>sessionFactoryBeanName</param-name>
          <param-value>sessionFactory</param-value>
        </init-param>
      </filter>


       <filter-mapping>
         <filter-name>hibernateFilter</filter-name>
         <url-pattern>/*</url-pattern>
         <dispatcher>REQUEST</dispatcher>
         <dispatcher>FORWARD</dispatcher>
       </filter-mapping>

的applicationContext.xml

<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan"
        value="com.mypack.common.model, com.mypack.school.model" />
        .
        .
        <!-- Other properties -->
        .
</bean>

customer.xhtml

XHTML用户界面有自动完成框,显示客户代码。自动完成查询使用CompleteCustomer方法,而转换器bean调用getCustomerbyCode。

选择客户代码后,屏幕将由选定的客户详细信息填充。允许应用程序用户在数据库中进行更改并保存更新。

CustomerBean.java

@ManagedBean (name="customerBean")
@ViewScoped
public class CustomerBean implements Serializable {

    public List<Customer> completeCustomer(String query) {
        List<Customer> suggestions;

        suggestions = (List<Customer>) customerService.getCustomerslikeCodeOrName(query, authenticationBean.getTenantId());

        return suggestions;
    }

    public void saveCustomerDetails() {
        // Save or Update User Information in Database
        customerService.saveCustomer(custMaster);
        return;            
    }

CustomerServiceImpl.java

@Service("customerService")
@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerDAO custMasterDAO;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void saveCustomer(Customer custDetails) {
        custMasterDAO.saveCustomer(custDetails);
    }

    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        return custMasterDAO.getCustomerbyCode(custCode, tenantId);
    }

    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        return custMasterDAO.getCustomerslikeCodeOrName(custIDName, tenantId);
    }
}

CustomerMasterDAO.java

    @SuppressWarnings("unchecked")
    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        List<Customer> listCustomers = null;
        custIDName = "%" + custIDName + "%";

        Session session = SessionFactoryUtils.getSession(sessionFactory, false);
        Transaction tx = session.beginTransaction();

        try {   
            query = session.createQuery("from Customer " +
                    "where (custId like :codename " +
                    "or custFirstName like :codename " +
                    "or custMiddleName like :codename " +
                    "or custLastName like :codename)")
                .setParameter("codename", custIDName);
            listCustomers = query.list();

        } catch(Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerslikeCodeOrName ***" + ex.getMessage());
        }

        return listCustomers;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        List<Customer> list = null ;
        Query query;

        Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
        Transaction tx = session.beginTransaction();

        Filter sessionFilter = session.enableFilter("BankRecordFilter");
        sessionFilter.setParameter("bankCode", tenantId.getBankCode());

        try {
            query = session.createQuery("from Customer where custId = :custCode");
            list = query.setParameter("custCode", custCode).list();
        } catch (Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerbyCode ***" + ex.getMessage());
        }
        if (list == null || list.size() < 1){
//          System.out.println("No Records Found");
            return null;
        }
        return (Customer)list.get(0);
    }

    @Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();  
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

    }

表格定义存储在.hbm.xml文件中。

我已经尝试了很多组合来放置以下语句来获取会话:     session = getSessionFactory()。getCurrentSession();     Session session = SessionFactoryUtils.getSession(sessionFactory,Boolean.FALSE);

还以不同的方式和不同的位置进行交易。我要么收到No Session的错误消息,要么两个或更多会话附加错误消息。

请告诉我我的代码有什么问题。

此致

希里什

2 个答案:

答案 0 :(得分:0)

最后我可以使用OpensessionInView。在这个问题上花了很多时间之后,我观察到LAZY加载是按照预期进行的,但是当我试图保存日期时,Session没有正确传播。

更新传播策略后,代码开始工作..这是更新的代码

@Transactional(readOnly = false,propagation = Propagation.NESTED)
@Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();  
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

答案 1 :(得分:0)

您正在混合用于事务处理和程序化事务处理的注释。看起来您的注释根本就没用过......