All applications using hibernate need save and update to interact with the database. For save, I will check the existence for some criteria. If it doesn't exist, I will save. For update, I will check the existence and certain criteria to determine whether update or not. What is the best practice to do the check and save / update?
I am currently creating a separate function that open a session and search to determine the existence. The session open/close is very clumsy. I think there should be better way to do it.
public Event searchByDateAddress(Date _date, String _address, boolean _closeSess)
{
    try
    {
        if(!session.isOpen())
        {
            session = HibernateUtil.getSessionFactory().openSession();
        }
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Event.class);
        criteria.add(Restrictions.eq("date", _date));
        criteria.add(Restrictions.eq("address", _address));
        criteria.setFetchMode("organizerProfile", FetchMode.JOIN);
        Event evt = (Event)criteria.uniqueResult();
        if(_closeSess)
        {
            session.close();
        }
        if (evt==null)
        {
            LogUtils.logInfo("The event does not exist: " + _date + " " + _address);
            return null;
        }
        else
        {
            return evt;
        }
    }
    catch(Exception e)
    {
        LogUtils.logInfo(e.toString());
        if(_closeSess)
        {
            session.close();
        }
        return null;
    }
}
public EventDTO insertEvent(Event _event)
{
    try
    {
        Event tmpEvent=new Event();
        //Event not exists
        if((tmpEvent=this.searchByDateAddress(_event.getDate(), _event.getAddress(), true))==null)
        {
            //insert
            if(!session.isOpen())
            {
                session = HibernateUtil.getSessionFactory().openSession();
            }
            Transaction tx=session.beginTransaction();
            long retOid=(Long)session.save(_event);
            session.flush();
            tx.commit();
            session.close();
            _event.setOid(retOid);
            return new EventDTO(_event);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
        session.close();
    }
    return new EventDTO();
}
Thanks