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

Java tutorial

Introduction

Here is the source code for cz.muni.pa165.carparkapp.DAOImpl.LoanDAOImpl.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.LoanDAO;
import cz.muni.pa165.carparkapp.Entities.Loan;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Repository;

/**
 * 
 * @author Michal, 374003
 */

@Repository("loanDAO")
@Transactional
public class LoanDAOImpl implements LoanDAO {

    @PersistenceContext
    private EntityManager em;

    public LoanDAOImpl() {
    }

    public EntityManager getEm() {
        return em;
    }

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

    @Override
    public Loan addLoan(Loan loan) {
        if (loan == null) {
            throw new NullPointerException("Argument can't be null");
        }
        em.persist(loan);
        return loan;
    }

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

    @Override
    public Loan getLoanById(int id) {
        if (id < 0) {
            throw new IllegalArgumentException("Id must be positive number");
        }
        Loan loan = em.find(Loan.class, id);

        return loan;
    }

    @Override
    public boolean deleteLoan(Loan loan) {
        if (loan == null) {
            throw new NullPointerException("Loan can't be null");
        }
        if (em.find(Loan.class, loan.getId()) != null) {
            em.remove(em.find(Loan.class, loan.getId()));
            return true;
        }
        return false;
    }

    @Override
    public List<Loan> getListOfLoans() {
        List<Loan> allLoans = em.createQuery("SELECT l FROM Loan l", Loan.class).getResultList();
        return allLoans;

    }
}