it.geosdi.era.server.dao.hibernate.DAOUtenteHibernate.java Source code

Java tutorial

Introduction

Here is the source code for it.geosdi.era.server.dao.hibernate.DAOUtenteHibernate.java

Source

/*
 *  GeoSDI ERA - The new era of webGIS
 *  http://code.google.com/p/geosdiera/
 * ====================================================================
 *
 * Copyright (C) 2008-2009 GeoSDI Group (CNR IMAA).
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. 
 *
 * ====================================================================
 *
 * This software consists of voluntary contributions made by developers
 * of GeoSDI Group.  For more information on GeoSDI, please see
 * <http://www.geosdi.org/>.
 *
 */

package it.geosdi.era.server.dao.hibernate;

import it.geosdi.era.client.Costanti;
import it.geosdi.era.client.model.Utente;
import it.geosdi.era.client.model.UtenteProgetto;
import it.geosdi.era.exception.DAOException;
import it.geosdi.era.server.dao.IDAOUtente;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class DAOUtenteHibernate implements IDAOUtente {

    /** LOGGER **/
    private static Log logger = LogFactory.getLog(DAOUtenteHibernate.class);

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

    private Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    // -------------------------------------------------------------------------
    //
    // Public interface
    //
    // -------------------------------------------------------------------------
    /**
     * Load the user with the argument ID
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente loadUser(Long id) {
        Session session = getSession();
        Query query = session.createQuery(
                "select utente from Utente utente left join fetch utente.utentiProgetto utentiProgetto where utente.id = ?");
        query.setLong(0, id);
        return (Utente) query.uniqueResult();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void flush(Utente utente) {
        getSession().evict(utente);
    }

    /**
     * Load the user with the argument login
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente findUtenteByUserName(String login) {
        // Create query
        //
        /*
         * StringBuffer hqlQuery = new StringBuffer();
         * hqlQuery.append("select utente from Utente utente");
         * hqlQuery.append(" left join fetch utente.progetti");
         * hqlQuery.append(" where utente.nomeUtente=:login");
         * 
         * // Fill query // Query query =
         * _entityManager.createQuery(hqlQuery.toString());
         * query.setParameter("login", login);
         */
        // Execute query
        //
        return null;// (Utente) query.getSingleResult();
    }

    /**
     * Load all the users
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Utente> loadAll() {
        // Create query
        //
        // Query query = _entityManager.createQuery("from Utente utente");

        // Execute query
        //
        return null;// (List<Utente>) query.getResultList();
    }

    /**
     * Count all the users
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public int countAll() {
        // Create query
        //
        /*
         * Query query = _entityManager
         * .createQuery("select count(*) from Utente utente");
         */

        // Execute query
        //
        return 0;// ((Long) query.getSingleResult()).intValue();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public int countAllUtentiProgetto(long id) {
        Session session = getSession();
        Query query = session
                .createQuery("select count(*) from UtenteProgetto utenteProgetto where utenteProgetto.utente = ? ");
        query.setLong(0, id);
        return ((Long) query.uniqueResult()).intValue();
    }

    /**
     * Save the argument user
     * 
     * @param user
     *            the user to save or create
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Utente saveUser(Utente user) {
        return this.makePersistent(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUser(Utente user) {
        makePersistent(user);
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente searchUserByLogin(String login) throws DAOException {
        try {
            Session session = getSession();
            Query query = session.createQuery(
                    "select utente from Utente utente left join fetch utente.utentiProgetto utentiProgetto where utente.userName = ?");
            query.setParameter(0, login);
            List<Utente> listaUtenti = (List<Utente>) query.list();
            if (listaUtenti.size() != 0)
                return listaUtenti.get(0);
        } catch (HibernateException e) {
            logger.error(Costanti.EXCEPTION_ERROR + e.getMessage());
            throw new DAOException(e.getMessage());
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<UtenteProgetto> loadUtentiProgetto(long id) {
        List<UtenteProgetto> listaUtentiProgetto = new ArrayList<UtenteProgetto>();
        Session session = getSession();
        Query query = session.createQuery(
                "select utenteProgetto from UtenteProgetto utenteProgetto where utenteProgetto.utente = ?");
        query.setLong(0, id);
        listaUtentiProgetto = query.list();
        return listaUtentiProgetto;
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Utente> getUsers(long id) {
        List<Utente> listaUtenti = new ArrayList<Utente>();
        Session session = getSession();
        Query query = session.createQuery(
                "select distinct utente from Utente utente left join fetch utente.utentiProgetto where utente.id != ? and utente.userName != 'test'");
        query.setLong(0, id);
        listaUtenti = query.list();
        return listaUtenti;

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void inizializzaProgetti(Utente utente) throws DAOException {
        try {
            // Hibernate.initialize(utente.getUtentiProgetto());
            getSession().get(Utente.class, utente.getId());
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Utente> findAll() throws DAOException {
        return findByCriteria(Restrictions.ne("userName", "test"));
    }

    public List<Utente> findAll(int offset, int limite) throws DAOException {
        return findByCriteria(offset, limite);
    }

    public Utente findById(Long id, boolean lock) throws DAOException {
        Utente entity;
        try {
            if (lock) {
                entity = (Utente) getSession().load(Utente.class, id, LockMode.UPGRADE);
            } else {
                entity = (Utente) getSession().load(Utente.class, id);
            }
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
        return entity;
    }

    public void lock(Utente entity) throws DAOException {
        try {
            getSession().lock(entity, LockMode.UPGRADE);
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
    }

    public Utente makePersistent(Utente entity) throws DAOException {
        try {
            getSession().saveOrUpdate(entity);
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
        return entity;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void makeTransient(Utente entity) throws DAOException {
        try {
            getSession().delete(entity);
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Utente> findByCriteria(Criterion... criterion) throws DAOException {
        try {
            Criteria crit = getSession().createCriteria(Utente.class);
            for (Criterion c : criterion) {
                crit.add(c);
            }
            return crit.list();
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Utente> findByCriteria(int offset, int limite, Criterion... criterion) throws DAOException {
        try {
            Criteria crit = getSession().createCriteria(Utente.class);
            for (Criterion c : criterion) {
                crit.add(c);
            }
            crit.setFirstResult(offset);
            crit.setMaxResults(limite);
            return crit.list();
        } catch (HibernateException ex) {
            throw new DAOException(ex);
        }
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente inizializzaUtentiProgetto(Utente utente) throws DAOException {
        try {
            Session session = getSession();
            Query query = session.createQuery(
                    "select utente from Utente utente left join fetch utente.utentiProgetto where utente.id = ?");
            query.setLong(0, utente.getId());
            List<Utente> listaUtenti = query.list();
            if (listaUtenti.size() != 0)
                return listaUtenti.get(0);
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente findById(Long userId) throws DAOException {
        try {
            List<Utente> userList = getSession().createCriteria(Utente.class).add(Restrictions.idEq(userId)).list();
            if (userList.size() > 0)
                return userList.get(0);
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.SUPPORTS)
    public Utente findByUserName(String userName) throws DAOException {
        try {
            List<Utente> userList = getSession().createCriteria(Utente.class)
                    .add(Restrictions.eq("userName", userName)).list();
            if (userList.size() > 0)
                return userList.get(0);
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
        return null;
    }
}