I want to remove a parent record and remove its children together, but removing the parent record has the following error
20: 26: 25,703 INFO [stdout] (default task-5) org.hibernate.HibernateException: Illegal attempt to associate with collection with two open sessions. Collection: [org.salomao.model.Post.midia # 1]
package org.salomao.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Formula;
@Entity
public class Postagem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(columnDefinition = "text")
private String conteudo;
@ManyToOne()
private Usuario usuario;
@OneToOne
private PostagemExterna postagemExterna;
@OneToMany(targetEntity = Midia.class, fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@Fetch(FetchMode.SELECT)
private List<Midia> midia;
private LocalDateTime dataPostagem;
@NotBlank(message = "Campo tags e obrigatório")
private String tags;
@ManyToMany(targetEntity = Politico.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@NotNull(message = "É obrigatório ter politicos")
@Fetch(FetchMode.SELECT)
@Column(unique = false)
private List<Politico> politicos;
@OneToMany( targetEntity = AvaliacaoPostagem.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL )
@Fetch(FetchMode.SELECT)
private List<AvaliacaoPostagem> avaliacoes;
@OneToMany(targetEntity = Comentario.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(FetchMode.SELECT)
private List<Comentario> comentarios;
@OneToMany( targetEntity = Marcadores.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(FetchMode.SELECT)
private List<Marcadores> marcadores;
@NotNull(message="e obrigatório devinir um tipo")
private String Tipo;
@Formula("(select AVG(a.nota) from AvaliacaoPostagem a where a.postagem_id = id )")
private Float media;
@OneToMany( targetEntity = Denuncia.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Fetch(FetchMode.SELECT)
private List<Denuncia> denuncias;
// @Formula(" (select AVG(Av_media) from (select AVG(av.nota) AS Av_media "
// + " from AvaliacaoComentario as av where av.comentario_id in (select c.id
// from Comentario c where c.postagem_id = id)) AS C_media ) ")
// @Formula( " (AVG((select AVG(av.nota) from AvaliacaoComentario av where
// av.comentario_id in (select c.id from Comentario c where c.postagem_id =
// id))) ) ")
@Formula(" (mediacomentariogeral(id)) ")
private Float mediaComentario;
private boolean desqualificada;
private boolean status;
/**
* @return the denuncias
*/
public List<Denuncia> getDenuncias() {
return denuncias;
}
public void setMedia(Float media) {
this.media = media;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getConteudo() {
return conteudo;
}
public void setConteudo(String conteudo) {
this.conteudo = conteudo;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public PostagemExterna getPostagemExterna() {
return postagemExterna;
}
public void setPostagemExterna(PostagemExterna postagemExterna) {
this.postagemExterna = postagemExterna;
}
public List<Midia> getMidia() {
return midia;
}
public void setMidia(List<Midia> midia) {
this.midia = midia;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public List<Politico> getPoliticos() {
return politicos;
}
public void setPoliticos(List<Politico> politicos) {
this.politicos = politicos;
}
public List<AvaliacaoPostagem> getAvaliacoes() {
return avaliacoes;
}
public void setAvaliacoes(List<AvaliacaoPostagem> avaliacoes) {
this.avaliacoes = avaliacoes;
}
public List<Comentario> getComentarios() {
return comentarios;
}
public void setComentarios(List<Comentario> comentarios) {
this.comentarios = comentarios;
}
/**
* @return the dataPostagem
*/
public LocalDateTime getDataPostagem() {
return dataPostagem;
}
/**
* @param dataPostagem
* the dataPostagem to set
*/
public void setDataPostagem(LocalDateTime dataPostagem) {
this.dataPostagem = dataPostagem;
}
/**
* @return the marcadores
*/
public List<Marcadores> getMarcadores() {
return marcadores;
}
/**
* @param marcadores
* the marcadores to set
*/
public void setMarcadores(List<Marcadores> marcadores) {
this.marcadores = marcadores;
}
/**
* @return the media
*/
public Float getMedia() {
return media;
}
/**
* @return the mediaComentario
*/
public Float getMediaComentario() {
return mediaComentario;
}
/**
* @param mediaComentario
* the mediaComentario to set
*/
public void setMediaComentario(Float mediaComentario) {
this.mediaComentario = mediaComentario;
}
/**
* @param media
* the media to set
*/
/**
* @param denuncias the denuncias to set
*/
public void setDenuncias(List<Denuncia> denuncias) {
this.denuncias = denuncias;
}
/**
* @return the desqualificada
*/
public boolean isDesqualificada() {
return desqualificada;
}
/**
* @param desqualificada the desqualificada to set
*/
public void setDesqualificada(boolean desqualificada) {
this.desqualificada = desqualificada;
}
/**
* @return the status
*/
public boolean isStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(boolean status) {
this.status = status;
}
/**
* @return the tipo
*/
public String getTipo() {
return Tipo;
}
/**
* @param tipo the tipo to set
*/
public void setTipo(String tipo) {
Tipo = tipo;
}
}
OBS child class happens with all child classes
package org.salomao.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Midia implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private byte[] conteudo;
private String nome;
private String extencao;
@ManyToOne
@JoinColumn(name = "postagem_id")
private Postagem postagem;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte[] getConteudo() {
return conteudo;
}
public void setConteudo(byte[] conteudo) {
this.conteudo = conteudo;
}
public Postagem getPostagem() {
return postagem;
}
public void setPostagem(Postagem postagem) {
this.postagem = postagem;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the extencao
*/
public String getExtencao() {
return extencao;
}
/**
* @param extencao the extencao to set
*/
public void setExtencao(String extencao) {
this.extencao = extencao;
}
}
My generic persistence class
package org.salomao.repository;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
abstract class Repository<T extends Object> implements Serializable {
private static final long serialVersionUID = 1L;
private Class<T> persistentClass;
private String className;
public Repository() {
// TODO Auto-generated constructor stub
@SuppressWarnings("unchecked")
Class<T> persistentClass2 = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
String s = ((ParameterizedType) superclass).getActualTypeArguments()[0].toString();
int inicio = s.lastIndexOf(".") + 1;
int fim = s.length();
className = s.substring(inicio, fim);
setPersistentClass(persistentClass2);
}
public T carregar(Object key) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
T r;
try {
transaction = session.beginTransaction();
// key = session.find(persistentClass, key);
r = session.find(persistentClass, key);
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
if (transaction != null)
transaction.rollback();
if(e instanceof NoResultException) {
throw new Exception("Não exite " + className + " com este código");
}
throw new Exception("Falha ao Carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return r ;
}
public T carregar(String key) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
T result = null;
try {
transaction = session.beginTransaction();
// key = session.find(persistentClass, key);
result = session.find(persistentClass, key);
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
transaction.rollback();
if(e instanceof NoResultException) {
throw new Exception("Não exite " + className + " com este código");
}
throw new Exception("Falha ao Carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return result;
}
public T carregar(long key) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
T result = null;
try {
transaction = session.beginTransaction();
// key = session.find(persistentClass, key);
result = session.find(persistentClass, key);
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
transaction.rollback();
if(e instanceof NoResultException) {
throw new Exception("Não exite " + className + " com este código");
}
throw new Exception("Falha ao Carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return result;
}
public T salvar(T entity) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.saveOrUpdate(entity);
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
System.out.println(e.getMessage());
if (transaction != null)
transaction.rollback();
if (session != null)
session.cancelQuery();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return entity;
}
public List<T> salvar(List<T> entitys) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
for (T t : entitys) {
session.saveOrUpdate(t);
session.flush();
session.clear();
}
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if (transaction != null)
transaction.rollback();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return entitys;
}
public void salvarOuAlterar(T entity) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.saveOrUpdate(entity);
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
e.printStackTrace();
if (transaction != null)
transaction.rollback();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
session.close();
}
}
@SuppressWarnings("unchecked")
public T alterar(T entity) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Object result = null;
try {
transaction = session.beginTransaction();
result = session.merge(entity);
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
if (transaction != null)
transaction.rollback();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return (T) result;
}
public void excluir(T entity) throws Exception {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = null;
//Object object = null;
try {
transaction = session.beginTransaction();
session.remove(entity);
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
transaction.rollback();
System.out.println(e.getMessage());
throw new Exception("Falha ao deletar " + className + ": " + e.getMessage());
} finally {
session.close();
}
}
public List<T> excluir(List<T> entitys) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
for (T t : entitys) {
session.delete(t);
session.flush();
session.clear();
}
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if (transaction != null)
transaction.rollback();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return entitys;
}
public List<T> findAll() throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
List<T> list = new ArrayList<T>();
TypedQuery<T> query;
try {
//session.ge
query = session.createQuery("from "+className, persistentClass);
list = query.getResultList();
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
if (transaction.isActive())
transaction.rollback();
throw new Exception("Falha ao carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return list;
}
public List<T> findAllOrderBy(String campo) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
List<T> list = new ArrayList<T>();
TypedQuery<T> query;
try {
//session.ge
query = session.createQuery("from "+className+" ORDER BY "+campo+" ASC" , persistentClass);
list = query.getResultList();
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
if (transaction.isActive())
transaction.rollback();
throw new Exception("Falha ao carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return list;
}
public List<T> findAllOrdByDesc(String campo) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
List<T> list = new ArrayList<T>();
TypedQuery<T> query;
try {
//session.ge
query = session.createQuery("from "+className+" ORDER BY "+campo+" DESC", persistentClass);
list = query.getResultList();
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
if (transaction.isActive())
transaction.rollback();
throw new Exception("Falha ao carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return list;
}
public List<T> findAll(int max) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
List<T> list = new ArrayList<T>();
TypedQuery<T> query;
try {
//session.ge
query = session.createQuery("from "+className, persistentClass);
query.setMaxResults(max);
list = query.getResultList();
session.flush();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
if (transaction != null)
if (transaction.isActive())
transaction.rollback();
throw new Exception("Falha ao carregar " + className + ": " + e.getMessage());
} finally {
session.close();
}
return list;
}
protected TypedQuery<T> criarQuery(String query) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
// Transaction transaction = null;
TypedQuery<T> query2;
try {
query2 = session.createQuery(query, persistentClass);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("Falha ao Criar Query " + className + ": " + e.getMessage());
} finally {
}
return query2;
}
protected Query criarQueryNativa(String query) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Query query2;
try {
query2 = session.createQuery(query, persistentClass);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
// session.close();
}
return query2;
}
protected Query criarQueryNativaNoPessiteClass(String query) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Query query2;
try {
query2 = session.createQuery(query);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
// session.close();
}
return query2;
}
protected void ExcutarSQL(String query) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Query query2 = null;
try {
query2 = session.createNativeQuery(query);
query2.executeUpdate();
if (transaction.isActive())
transaction.commit();
} catch (Exception e) {
// TODO: handle exception
if (transaction != null)
if (transaction.isActive())
transaction.rollback();
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
// session.close();
}
}
protected TypedQuery<T> criarQuery(String query,Class<T> tipo) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
// Transaction transaction = null;
TypedQuery<T> query2;
try {
query2 = session.createQuery(query, tipo);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("Falha ao Criar Query " + className + ": " + e.getMessage());
} finally {
}
return query2;
}
protected Query criarQueryNativa(String query,Class<T> tipo) throws Exception {
Session session = HibernateUtil.getSessionFactory().openSession();
// Transaction transaction = null;
Query query2;
try {
query2 = session.createNativeQuery(query, tipo);
} catch (Exception e) {
// TODO: handle exception
throw new Exception("Falha ao Salvar " + className + ": " + e.getMessage());
} finally {
// session.close();
}
return query2;
}
/**
* @return the persistentClass
*/
public Class<T> getPersistentClass() {
return persistentClass;
}
/**
* @param persistentClass
* the persistentClass to set
*/
public void setPersistentClass(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @param className
* the className to set
*/
public void setClassName(String className) {
this.className = className;
}
}