struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From pirzada rashid <pirzada.ras...@gmail.com>
Subject DAOImpl for hibernate got few general and specific questions
Date Fri, 14 Sep 2012 19:16:39 GMT
Hi,

I have CustomerDAOImpl where I am doing CRUD. Few questions.

*Q1 -* Should I declare Session at class level or each method level OR
declare at class level and initialize at each method level?

*Q2 -* When fetching data like in listCustomer, Should I
session.beginTransaction(); and than commit it? . I think on fetch,
transaction shouldn't apply but if I am not atleast
session.beginTransaction(); gives error saying need active transaction.

*Q3 -* I have read that session is expensive and should not close it till
application is running. Where should I close and open it if not using
Spring etc?

*Q4 -* I get *WARNING* Note:
C:\Struts2_HelloWorld\src\com\myapp\dao\CustomerDAOImpl.java uses unchecked
or unsafe operations. Why is that and how to fix this?

*if you answer most of my problems will be clear. Thanks*

*CustomerDAOImpl.java*

package com.myapp.dao;

import com.myapp.model.Customer;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class CustomerDAOImpl implements CustomerDAO {

    Session session = HibernateUtil.getFactory().getCurrentSession();
    Transaction tx = null;

    //add the customer
    public void addCustomer(Customer customer) {
        tx = session.beginTransaction();
        try {
            session.save(customer);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        }
    }

    //return all the customers in list
    public List<Customer> listCustomer() {
        tx = session.beginTransaction();
        return session.createQuery("from Customer").list();
    }
}

*HibernateUtil.java*

package com.myapp.dao;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory factory = getSessionFactory();
    private static ServiceRegistry serviceRegistry;

    private static synchronized SessionFactory getSessionFactory()
throws HibernateException {
        Configuration configuration = new Configuration().configure();
        serviceRegistry = new
ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        return configuration.buildSessionFactory(serviceRegistry);
    }

    public static SessionFactory getFactory() {
        return factory;
    }


}

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message