springhibernatelazy-loadingopen-session-in-view

Issues with OpenSessionInView


I have implemented Spring/Hibernate's OpenSessionInView Pattern for Lazy Loading. I am facing either "No Sessoon" or "2 or more sessions" issue. Let me know If I am missing any steps:

Here are detail code fragments:

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 user interface has autocomplete box showing customer code. Autocomplete query make use of CompleteCustomer Method, whereas getCustomerbyCode is called by converter bean.

Upon selection of cust code, screen is populated by selected customer details. Application User is allowed to make changes and save updates in DB.

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

    }

Table definations are stored in .hbm.xml files.

I have tried lot of combinations of placing following statements to get session: session = getSessionFactory().getCurrentSession(); Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);

Also transaction in different ways and different location. I am either getting error messages for No Session or Two or more sessions are attached error message.

Can you please let me know what is wrong with my code.

Regards,

Shirish


Solution

  • Finally I am able to use OpensessionInView. After spending lot of time on this issue, I observed that LAZY loading was working as per expection, but when I am trying to save date, Session was not properly propagted.

    After updating propagation strategy, code started working.. Here is updated code

    @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();
            }