com.ori.outlierserver.dao.ReadingsDao.java Source code

Java tutorial

Introduction

Here is the source code for com.ori.outlierserver.dao.ReadingsDao.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ori.outlierserver.dao;

import com.ori.outlierserver.dto.Reading;
import com.ori.outlierserver.utils.HibernateUtil;
import java.util.Collections;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Haim
 */
public class ReadingsDao {

    private static final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Reading> getLastNReadingsByClientId(String clientId, int N) {
        List<Reading> theReadingList = null;
        Session theSession = null;
        if (N <= 0) {
            return Collections.<Reading>emptyList();
        }
        try {
            theSession = sessionFactory.openSession();
            theSession.beginTransaction();
            String sql = "SELECT * FROM readings WHERE client_id = :id limit :lim";
            SQLQuery query = theSession.createSQLQuery(sql);
            query.addEntity(Reading.class);
            query.setString("id", clientId);
            query.setInteger("lim", N);
            theReadingList = query.list();
            theSession.getTransaction().commit();
        } catch (Exception e) {
            if (theSession != null) {
                theSession.getTransaction().rollback();
            }
        } finally {
            if (theSession != null) {
                theSession.close();
            }
        }
        return theReadingList;
    }
}