Java tutorial
/* * 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 cz.muni.pa165.carparkapp.DAOImpl; import cz.muni.pa165.carparkapp.DAO.EmployeeDAO; import cz.muni.pa165.carparkapp.Entities.Employee; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import org.apache.commons.lang3.Validate; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; /** * * @author Martin Lisy, 396280 */ @Repository("employeeDAO") @Transactional public class EmployeeDAOImpl implements EmployeeDAO { @PersistenceContext private EntityManager em; public EmployeeDAOImpl() { } public void setEm(EntityManager em) { this.em = em; } public EntityManager getEm() { return em; } @Override public List<Employee> getAllEmployees() { List<Employee> employees = null; try { employees = em.createQuery("SELECT e FROM Employee e", Employee.class).getResultList(); } catch (Exception e) { throw new DataAccessException("Exception during getting Employees from DB") { }; } return employees; } @Override public Employee findEmployeeById(int id) { Validate.isTrue(id > 0, "Employees's ID cannot be null!"); Query query = em.createQuery("select e from Employee e " + "where e.id = ?1").setParameter(1, id); if (query.getResultList() == null) { throw new IllegalArgumentException("Error in query during employee finding"); } if (query.getResultList().size() != 1) { throw new IllegalArgumentException("No such employee was found"); } return ((List<Employee>) query.getResultList()).get(0); } @Override public boolean updateEmployee(Employee employee) { Validate.isTrue(employee != null, "Employee cannot be null!"); Validate.isTrue(employee.getId() != -1, "Employee's ID cannot be null!"); em.merge(employee); return true; } @Override public boolean deleteEmployee(Employee employee) { Validate.isTrue(employee != null, "Employee cannot be null!"); Validate.isTrue(employee.getId() != -1, "Employee's ID cannot be null!"); em.remove(em.merge(employee)); return true; } @Override public Employee addEmployee(Employee employee) { Validate.isTrue(employee != null, "Employee cannot be null!"); em.persist(employee); return employee; } }