package com.rwd.springFlow4B.dao.user;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import com.rwd.springFlow4B.model.User;

//@org.springframework.stereotype.Repository // transaction is NOT workable!
public class UserDaoJpaEmFactoryImpl implements UserDao {

	@PersistenceUnit
	private EntityManagerFactory emf;

	@Override
	public User findById(Integer id) {
		if (id == null)
			return null;
		return emf.createEntityManager().find(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() {
		return emf.createEntityManager().createQuery("from User").getResultList();
	}

	@Override
	public User create(User user) {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(user);
		em.flush();
		em.getTransaction().commit();
		em.close();
		return user;
	}

	@Override
	public User update(User user) {
		EntityManager em = emf.createEntityManager();
		em.merge(user);
		em.flush();
		return user;
	}

	@Override
	public void delete(Integer id) {
		EntityManager em = emf.createEntityManager();
		User u = em.find(User.class, id);
		em.remove(u);
		em.flush();
	}

}