com.github.leonardoxh.temporeal.model.dao.Dao.java Source code

Java tutorial

Introduction

Here is the source code for com.github.leonardoxh.temporeal.model.dao.Dao.java

Source

/*
 * Copyright 2014 Leonardo Rossetto
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.leonardoxh.temporeal.model.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.github.leonardoxh.temporeal.model.Model;
import com.github.leonardoxh.temporeal.model.hibernate.HibernateUtils;

public abstract class Dao {

    @SuppressWarnings("unchecked")
    public static <T extends Model> List<T> fetchAll(Class<T> model) {
        Session currentSession = HibernateUtils.getCurrentSession();
        initTransaction(currentSession);
        List<T> items = currentSession.createCriteria(model).list();
        currentSession.close();
        return items;
    }

    public static <T> Object get(Long id, Class<T> clazz) {
        Session currentSession = HibernateUtils.getCurrentSession();
        initTransaction(currentSession);
        Object item = currentSession.get(clazz, id);
        currentSession.close();
        return item;
    }

    public static void saveOrUpdate(Model model) {
        Session currentSession = HibernateUtils.getCurrentSession();
        Transaction transaction = initTransaction(currentSession);
        try {
            currentSession.saveOrUpdate(model);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        }
    }

    public static Transaction initTransaction(Session currentSession) {
        Transaction currentTransaction = currentSession.getTransaction();
        if (currentTransaction != null) {
            if (currentTransaction.isActive()) {
                return currentTransaction;
            }
            currentTransaction.begin();
            return currentTransaction;
        }
        return currentSession.beginTransaction();
    }

}