package pl.bnsit.emtemplate;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;


public class EnityManagerTemplate {

	private EntityManager entityManager;
	
	public EnityManagerTemplate( EntityManager em ) {
		this.entityManager = em;
	}
	
	public void persist( final Object obj ) {
		
		EntityManagerCallback callback = new EntityManagerCallback() {
			public Object doInEntityManager() {
				entityManager.persist( obj );
				return null;
			}
		};
		
		invokeCallback( callback );
		
	}
	
	public List findByNamedQuery( final String namedQueryName ) {
		
		EntityManagerCallback callback = new EntityManagerCallback() {
			public Object doInEntityManager() {
				Query query = entityManager.createNamedQuery( namedQueryName );
				
				return query.getResultList();
			}
		};
		
		return (List) invokeCallback( callback );
		
	}
	
	protected Object invokeCallback( EntityManagerCallback callback ) {
		entityManager.getTransaction().begin();
		
		Object result = null;
		
		try {
			result = callback.doInEntityManager();
			entityManager.getTransaction().commit();
		} catch ( Exception e ) {
			entityManager.getTransaction().rollback();
		}
		
		return result;
	}
	
}
