com.portal.dao.DepartmentDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.portal.dao.DepartmentDAOImpl.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.portal.dao;

import java.util.List;
import com.portal.entity.Department;
import com.portal.exception.PortalException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;

/**
 *
 * @author Evgen
 */
public class DepartmentDAOImpl implements DepartmentDAO {

    private SessionFactory sessionFactory;

    public DepartmentDAOImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void saveDepartment(Department department) {
        sessionFactory.getCurrentSession().saveOrUpdate(department);
    }

    @Override
    public Department loadDepartment(int id) {
        Department department = null;
        try {
            department = (Department) sessionFactory.getCurrentSession().get(Department.class, id);
        } catch (Exception e) {

        }
        return department;
    }

    @Override
    public void deleteDepartment(int id) throws Exception {
        try {
            Query query = sessionFactory.getCurrentSession().createQuery("delete from Department where id=:id");
            query.setInteger("id", id);
            query.executeUpdate();
        } catch (ConstraintViolationException ex) {
            throw new PortalException(
                    "?  .   ???? ?.");
        }
    }

    @Override
    public List<Department> loadDepartments() {
        return sessionFactory.getCurrentSession().createQuery("from Department").list();
    }

}