Após todos os ajustes, não grava nem remove mais nenhum registro.
package br.com.caelum.livraria.dao;
import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtil implements Serializable{
private static EntityManagerFactory emf = Persistence
.createEntityManagerFactory("livraria");
@Produces
@RequestScoped
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void close(@Disposes EntityManager em) {
em.close();
}
}
package br.com.caelum.livraria.dao;
import java.util.List;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
public class DAO<T> implements Serializable{
private static final long serialVersionUID = 1L;
private final Class<T> classe;
private EntityManager manager;
public DAO(EntityManager manager, Class<T> classe) {
this.manager = manager;
this.classe = classe;
}
public void adiciona(T t) {
// persiste o objeto
manager.persist(t);
}
public void remove(T t) {
manager.remove(manager.merge(t));
}
public void atualiza(T t) {
manager.merge(t);
}
public List<T> listaTodos() {
CriteriaQuery<T> query = manager.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = manager.createQuery(query).getResultList();
return lista;
}
public T buscaPorId(Integer id) {
T instancia = manager.find(classe, id);
return instancia;
}
public int contaTodos() {
long result = (Long) manager.createQuery("select count(n) from livro n").getSingleResult();
return (int) result;
}
public List<T> listaTodosPaginada(int firstResult, int maxResults, Map<String, Object> filtros) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<T> query = builder.createQuery(classe);
Root<T> root = query.from(classe);
List<Predicate> predicates = new ArrayList<Predicate>();
for (Map.Entry<String, Object> entry : filtros.entrySet()) {
if (entry.getValue() != null) {
Path<String> field = root.<String> get(entry.getKey());
String valor = "%" + entry.getValue().toString() + "%";
Predicate predicate = builder.like(field, valor) ;
predicates.add(predicate);
}
}
query.where((Predicate[]) predicates.toArray(new Predicate[0]));
List<T> lista = manager.createQuery(query).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
return lista;
}
public int quantidadeDeElementos() {
long result = (Long) manager.createQuery("select count(n) from " + classe.getSimpleName() + " n").getSingleResult();
return (int) result;
}
}
package br.com.caelum.livraria.tx;
import java.io.Serializable;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
@SuppressWarnings("serial")
@Transacional
@Interceptor
public class GerenciadorDeTransacao implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Inject
EntityManager manager;
@AroundInvoke
public Object executaTx(InvocationContext context) throws Exception {
System.out.println("abrindo transacao");
manager.getTransaction().begin();
// chama os daos que precisam de transacao
Object result = context.proceed();
System.out.println("fechando transacao");
manager.getTransaction().commit();
return result;
}
}
package br.com.caelum.livraria.tx;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Transacional {
}
<beans>
<interceptors>
<class>br.com.caelum.livraria.tx.GerenciadorDeTransacao</class>
</interceptors>
</beans>
package br.com.caelum.livraria.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.caelum.livraria.dao.AutorDao;
import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.tx.Transacional;
@Named
@ViewScoped
public class AutorBean implements Serializable {
private static final long serialVersionUID = 1L;
private Autor autor = new Autor();
@Inject
private AutorDao autorDao;
private Integer autorId;
public Integer getAutorId() {
return autorId;
}
public void setAutorId(Integer autorId) {
this.autorId = autorId;
}
public void carregarAutorPelaId() {
this.autor = this.autorDao.buscaPorId(autorId);
}
@Transacional
public String gravar() {
System.out.println("Gravando autor " + this.autor.getNome());
if(this.autor.getId() == null) {
this.autorDao.adiciona(this.autor);
} else {
this.autorDao.atualiza(this.autor);
}
this.autor = new Autor();
return "livro?faces-redirect=true";
}
@Transacional
public void remover(Autor autor) {
System.out.println("Removendo autor " + autor.getNome());
this.autorDao.remove(autor);
}
public List<Autor> getAutores() {
return this.autorDao.listaTodos();
}
public Autor getAutor() {
return autor;
}
public void setAutor(Autor autor) {
this.autor = autor;
}
}