package com.nisum.dao.impl;

import com.nisum.dao.Dao;
import com.nisum.model.impl.EmployeeImp;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.Optional;

@Repository
@Qualifier("EmployeeDao")
@Transactional
public class EmployeeDao implements Dao<EmployeeImp> { //DAO - Data Access Object

  @PersistenceContext
  private EntityManager entityManager;

  @Override
  public Optional<EmployeeImp> getById(Integer id) {
    return Optional.of(entityManager.getReference(EmployeeImp.class, id));
  }

  @Override
  public Collection<EmployeeImp> getAll() {
    TypedQuery<EmployeeImp> typedQuery = entityManager.createQuery("SELECT e FROM employee e", EmployeeImp.class);
    return typedQuery.getResultList();
  }

  @Override
  public void save(EmployeeImp employeeImp) {
    entityManager.persist(employeeImp); //Persist - Spring's way of inserting to the database.
  }

  @Override
  public void update(EmployeeImp employeeImp) {
    entityManager.merge(employeeImp);
  }

  @Override
  public void delete(EmployeeImp employeeImp) {
    entityManager.remove(employeeImp);
  }
}
