cz.muni.pa165.carparkapp.DAOImpl.CarDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for cz.muni.pa165.carparkapp.DAOImpl.CarDAOImpl.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 cz.muni.pa165.carparkapp.DAOImpl;

import cz.muni.pa165.carparkapp.DAO.CarDAO;
import cz.muni.pa165.carparkapp.Entities.Car;
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 Tom Rcek, 396561
 */
@Repository("carDAO")
@Transactional
public class CarDAOImpl implements CarDAO {

    @PersistenceContext
    private EntityManager em;

    public CarDAOImpl() {
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public EntityManager getEm() {
        return em;
    }

    @Override
    public List<Car> getAllCars() {
        List<Car> cars = null;
        try {
            cars = em.createQuery("SELECT c FROM Car c", Car.class).getResultList();
        } catch (Exception e) {
            throw new DataAccessException("Query thrown exception") {
            };
        }
        return cars;
    }

    @Override
    public Car findCarById(int id) {
        Validate.isTrue(id > 0, "Car's ID cannot be null!");

        Query query = em.createQuery("select c from Car c " + "where c.id = ?1").setParameter(1, id);
        if (query.getResultList() == null) {
            throw new IllegalArgumentException("Error in query");
        }
        if (query.getResultList().size() != 1) {
            throw new IllegalArgumentException("No car found");
        }
        return ((List<Car>) query.getResultList()).get(0);
    }

    @Override
    public boolean deleteCar(Car car) {
        Validate.isTrue(car != null, "Car cannot be null!");
        Validate.isTrue(car.getId() != -1, "Car ID cannot be null!");
        em.remove(em.merge(car));
        return true;
    }

    @Override
    public boolean updateCar(Car car) {
        Validate.isTrue(car != null, "Car cannot be null!");
        Validate.isTrue(car.getId() != -1, "Car's ID cannot be null!");
        em.merge(car);
        return true;
    }

    @Override
    public Car addCar(Car car) {
        Validate.isTrue(car != null, "Car cannot be null!");
        em.persist(car);
        return car;
    }

}