struts-user mailing list archives

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

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\ uses unchecked
or unsafe operations. Why is that and how to fix this?

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


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 {
        } catch (HibernateException e) {
            if (tx != null) tx.rollback();

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


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
        return configuration.buildSessionFactory(serviceRegistry);

    public static SessionFactory getFactory() {
        return factory;


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