Solucionado (ver solução)
Solucionado
(ver solução)
12
respostas

Hibernate não retorna nenhum resultado ao tentar usar join fetch

Olá pessoal, tô com problemas ao tentar buscar uma entidade com uma lista de atributos preenchida (ou no meu caso, vazia se não tiver nada no banco ainda).

O método:

    public Tarefa carregaTarefaComInteracoes(Integer id) {
        TypedQuery<Tarefa> query = entityManager
                .createQuery("select distinct t from Tarefa t join fetch t.interacoes where t.id=:pId", Tarefa.class);
        query.setParameter("pId", id);
        return query.getSingleResult();
    }

Eu recebo uma ADVERTÊNCIA: #{interacaoBean.carregaTarefa}: javax.persistence.NoResultException: No entity found for query ao chama-lo.

A minha classe Tarefa mapeou a classe Interação da seguinte forma:

    @OneToMany
    private List<Interacao> interacoes;

Optei por deixar o relacionamento unidirecional e não mapeei a classe Interação com o atributo Tarefa.

Tô tentando fazer isso porque ao tentar salvar uma interação depois de carregar uma Tarefa normalmente eu recebo uma lazyinitializationexception

12 respostas

Bom dia Ygor, de acordo com a documentação, o método getSingleResult() retorna uma exception caso não tenha valor na consulta!

Throws: NoResultException - if there is no result

Dessa forma você precisa tratar com o try/catch

Abraços

Guilherme assunto meio que por fora agora, aonde que vocês acham essa documentação de cada metodo? Alias qualquer documentação aonde que é possivel achar?

Entendi Guilherme, eu vi que so nao tava devolvendo nada porque no banco eu nao tinha informações de nenhuma "Interação" pra entidade "Tarefa".

Mas agora continuo com o problema da LazyInitializationException.

Meu bean (JSF) ficou com o método para carregar a entidade da seguinte forma:

    public void carregaTarefa() {
        try {
            tarefa = tarefaDAO.carregaTarefaComInteracoes(tarefa.getId());
        } catch (NoResultException e) {
            System.out.println("A tarefa ainda não possui interações.");
            tarefa = tarefaDAO.buscaPorId(tarefa.getId());
        }

        if (tarefa == null) {
            tarefa = new Tarefa();
        }
    }

Meu método para atualizar minha entidade Tarefa com a nova "Interação" (lista):

    @Transactional
    public void salvarInteracao() {
        this.tarefa.getInteracoes().add(interacao);
        tarefaDAO.atualiza(tarefa);
    }

Queria saber como contornar isso. Não tô encontrando alguma forma. Eu vi algumas informações sobre o padrão "Open Session In View". Tô utilizando o spring framework em conjunto com o JSF e vi algo sobre a classe "OpenSessionInViewInterceptor". Alguém conhece a forma de trabalhar com essa classe pra fugir dessa exceção?

Pessoal, como as consultas são realizadas sob demanda, após eu concluir minha página .xhtml que possui um datatable pra exibir minha lista de "intreções" eu já não recebo a LazyInitializationException.

Agora ao salvar eu recebo: org.hibernate.TransientPropertyValueException Isso é porque minha entidade interação, a qual eu quero salvar com a Tarefa ainda é transient né? Eu sou obrigado a persistir minha Interação antes de adiciona-la à lista? Eu vi que se eu usar o CascadeType.ALL no mapeamento obteria êxito, mas não deu certo comigo haha :(

Ygor posta a classe modelo sua, e o seu bean e a classe dao?

Entidade Tarefa

package br.com.ygormagalhaes.sgcv.tarefas.model;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import br.com.ygormagalhaes.sgcv.pessoas.model.Usuario;
import br.com.ygormagalhaes.sgcv.projetos.model.Fase;
import br.com.ygormagalhaes.sgcv.projetos.model.Projeto;

@Entity
public class Tarefa implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;
    private String nome;
    @Column(columnDefinition = "text")
    private String descricao;
    @ManyToOne
    private Usuario responsavel = new Usuario();
    @Temporal(TemporalType.TIMESTAMP)
    private Calendar dataCriacao = Calendar.getInstance();
    @Temporal(TemporalType.TIMESTAMP)
    private Calendar dataPrazo = Calendar.getInstance();
    private Boolean finalizada = false;
    @ManyToOne
    private Projeto projeto = new Projeto();
    @ManyToOne
    private Fase fase = new Fase();
    @OneToMany(cascade = CascadeType.PERSIST)
    private List<Interacao> interacoes;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Usuario getResponsavel() {
        return responsavel;
    }

    public void setResponsavel(Usuario responsavel) {
        this.responsavel = responsavel;
    }

    public Calendar getDataCriacao() {
        return dataCriacao;
    }

    public void setDataCriacao(Calendar dataCriacao) {
        this.dataCriacao = dataCriacao;
    }

    public Calendar getDataPrazo() {
        return dataPrazo;
    }

    public void setDataPrazo(Calendar dataPrazo) {
        this.dataPrazo = dataPrazo;
    }

    public Boolean getFinalizada() {
        return finalizada;
    }

    public void setFinalizada(Boolean finalizada) {
        this.finalizada = finalizada;
    }

    public Projeto getProjeto() {
        return projeto;
    }

    public void setProjeto(Projeto projeto) {
        this.projeto = projeto;
    }

    public Fase getFase() {
        return fase;
    }

    public void setFase(Fase fase) {
        this.fase = fase;
    }

    public List<Interacao> getInteracoes() {
        return interacoes;
    }

    public void setInteracoes(List<Interacao> interacoes) {
        this.interacoes = interacoes;
    }

    @Override
    public String toString() {
        return "Tarefa [id=" + id + ", nome=" + nome + ", descricao=" + descricao + ", responsavel="
                + responsavel.getNome() + ", dataCriacao=" + dataCriacao + ", dataPrazo=" + dataPrazo + ", finalizada="
                + finalizada + "]";
    }

}

Entidade Interacao

package br.com.ygormagalhaes.sgcv.tarefas.model;

import java.io.Serializable;
import java.util.Calendar;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import br.com.ygormagalhaes.sgcv.pessoas.model.Usuario;

@Entity
public class Interacao implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;
    @ManyToOne
    private Usuario usuario = new Usuario();
    private Calendar dataEHora = Calendar.getInstance();
    @Column(columnDefinition = "text")
    private String texto;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public Calendar getDataEHora() {
        return dataEHora;
    }

    public void setDataEHora(Calendar dataEHora) {
        this.dataEHora = dataEHora;
    }

    public String getTexto() {
        return texto;
    }

    public void setTexto(String texto) {
        this.texto = texto;
    }

}

TarefaDAO

package br.com.ygormagalhaes.sgcv.tarefas.dao;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import br.com.ygormagalhaes.sgcv.dao.DAO;
import br.com.ygormagalhaes.sgcv.projetos.model.Projeto;
import br.com.ygormagalhaes.sgcv.tarefas.model.Tarefa;

@Repository
public class TarefaDAO implements Serializable {

    private static final long serialVersionUID = 1L;

    @PersistenceContext
    private EntityManager entityManager;
    private DAO<Tarefa> dao;

    @PostConstruct
    public void init() {
        dao = new DAO<Tarefa>(entityManager, Tarefa.class);
    }

    public void adiciona(Tarefa t) {
        dao.adiciona(t);
    }

    public void remove(Tarefa t) {
        dao.remove(t);
    }

    public void atualiza(Tarefa t) {
        dao.atualiza(t);
    }

    public List<Tarefa> listaTodos() {
        return dao.listaTodos();
    }

    public Tarefa buscaPorId(Integer id) {
        return dao.buscaPorId(id);
    }

    public int contaTodos() {
        return dao.contaTodos();
    }

    public List<Tarefa> listaTarefasPorProjeto(Projeto projeto) {
        TypedQuery<Tarefa> query = entityManager.createQuery("select t from Tarefa t where t.projeto=:pProjeto",
                Tarefa.class);
        query.setParameter("pProjeto", projeto);
        return query.getResultList();
    }

    public Tarefa carregaTarefaComInteracoes(Integer id) {
        TypedQuery<Tarefa> query = entityManager
                .createQuery("select distinct t from Tarefa t join fetch t.interacoes where t.id=:pId", Tarefa.class);
        query.setParameter("pId", id);
        return query.getSingleResult();
    }

}

DAO generico

package br.com.ygormagalhaes.sgcv.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class DAO<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    private final Class<T> classe;
    private EntityManager em;

    public DAO(EntityManager em, Class<T> classe) {
        this.em = em;
        this.classe = classe;
    }

    public void adiciona(T t) {
        em.persist(t);
    }

    public void remove(T t) {
        em.remove(em.merge(t));
    }

    public void atualiza(T t) {
        em.merge(t);
    }

    public List<T> listaTodos() {
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        query.select(query.from(classe));

        List<T> lista = em.createQuery(query).getResultList();

        return lista;
    }

    public T buscaPorId(Integer id) {
        T instancia = em.find(classe, id);
        return instancia;
    }

    public int contaTodos() {
        long result = (Long) em.createQuery("select count(n) from livro n").getSingleResult();

        return (int) result;
    }

    public List<T> listaTodosPaginada(int firstResult, int maxResults, String coluna, String valor) {
        CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
        Root<T> root = query.from(classe);

        if (valor != null)
            query = query.where(em.getCriteriaBuilder().like(root.<String>get(coluna), valor + "%"));

        System.out.println(coluna + " : " + valor);

        List<T> lista = em.createQuery(query).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();

        return lista;
    }

}

InteracaoBean

package br.com.ygormagalhaes.sgcv.tarefas.bean;

import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.persistence.NoResultException;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import br.com.ygormagalhaes.sgcv.tarefas.dao.TarefaDAO;
import br.com.ygormagalhaes.sgcv.tarefas.model.Interacao;
import br.com.ygormagalhaes.sgcv.tarefas.model.Tarefa;

@Controller
@ViewScoped
public class InteracaoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private TarefaDAO tarefaDAO;

    private Interacao interacao = new Interacao();

    private Tarefa tarefa = new Tarefa();

    public Tarefa getTarefa() {
        return tarefa;
    }

    public void setTarefa(Tarefa tarefa) {
        this.tarefa = tarefa;
    }

    public void carregaTarefa() {
        try {
            tarefa = tarefaDAO.carregaTarefaComInteracoes(tarefa.getId());
        } catch (NoResultException e) {
            System.out.println("A tarefa ainda não possui interações.");
            tarefa = tarefaDAO.buscaPorId(tarefa.getId());
        }

        if (tarefa == null) {
            tarefa = new Tarefa();
        }

    }

    public Interacao getInteracao() {
        return interacao;
    }

    public void setInteracao(Interacao interacao) {
        this.interacao = interacao;
    }

    // TODO lembrar de atualizar a futura lista de interações
    @Transactional
    public void salvarInteracao() {
        this.tarefa.getInteracoes().add(interacao);
        tarefaDAO.atualiza(tarefa);
    }

}

Ae Alisson as classes

Na classe que postei ficou com CascadeType.PERSIST mas já tentei com CascadeType.ALL também

Tá vamos por parte, no seu código já que você está usando CDI ou Spring seila algo assim correto? Então deixa esses frameworks fazerem o trabalho para você, por exemplo aqui,

   @Inject
    private TarefaDAO tarefaDAO;

    private Interacao interacao = new Interacao();

    private Tarefa tarefa = new Tarefa();

Deixa tudo igual a Classe TarefaDao kkk com o @inject. E você está tentando salvar ou alterar? Porque você está chamando o metodo

 tarefaDAO.atualiza(tarefa);
//Não seria o salvar algo assim?

Posta o erro aqui para gente, e também seu html para poder enteder mais esses codigos. E eu particularmente não gosto de usar Casdade.

Aqui a exception horrorosa:

ERROR: HHH000346: Error during managed flush [org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario]
abr 25, 2017 2:44:57 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{interacaoBean.salvarInteracao}: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
javax.faces.FacesException: #{interacaoBean.salvarInteracao}: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:178)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 33 more
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDialect.java:122)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at br.com.ygormagalhaes.sgcv.tarefas.bean.InteracaoBean$$EnhancerBySpringCGLIB$$846f7dc5.salvarInteracao(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 34 more
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:144)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    ... 50 more
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:380)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:119)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:414)
    at org.hibernate.event.internal.DefaultPersistEventListener.justCascade(DefaultPersistEventListener.java:171)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:164)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
    at org.hibernate.internal.SessionImpl.firePersistOnFlush(SessionImpl.java:833)
    at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:826)
    at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:341)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:391)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:316)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:424)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:356)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:319)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:104)
    at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:150)
    at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:141)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:74)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
    ... 59 more

abr 25, 2017 2:44:57 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.faces.el.EvaluationException: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:178)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDialect.java:122)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at br.com.ygormagalhaes.sgcv.tarefas.bean.InteracaoBean$$EnhancerBySpringCGLIB$$846f7dc5.salvarInteracao(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 34 more
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:144)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    ... 50 more
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance beforeQuery flushing : br.com.ygormagalhaes.sgcv.tarefas.model.Interacao.usuario -> br.com.ygormagalhaes.sgcv.pessoas.model.Usuario
    at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:380)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:119)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:414)
    at org.hibernate.event.internal.DefaultPersistEventListener.justCascade(DefaultPersistEventListener.java:171)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:164)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128)
    at org.hibernate.internal.SessionImpl.firePersistOnFlush(SessionImpl.java:833)
    at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:826)
    at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:341)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:391)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:316)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:424)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:356)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:319)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:155)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:104)
    at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:150)
    at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:141)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:74)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
    ... 59 more

A página xhtml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">
<h:head />
    <ui:composition template="../template/_template.xhtml">

    <f:metadata>
        <f:viewParam name="tarefaId" value="#{interacaoBean.tarefa.id}" id="tarefaId"/>
        <f:viewAction action="#{interacaoBean.carregaTarefa}" if="#{param.tarefaId != null}"/>
    </f:metadata>

        <ui:define name="conteudo">

            <h:form id="formCadastro">
                <p:panel header="Detalhes da Tarefa">
                    <p:panelGrid columns="6">

                        <h4>Nome</h4>
                        <h:outputText id="nome" value="#{interacaoBean.tarefa.nome}"/>

                        <h4>Responsável</h4>
                        <h:outputText id="responsavel" value="#{interacaoBean.tarefa.responsavel.nome}"/>

                        <h4>Projeto</h4>
                        <h:outputText id="projeto" value="#{interacaoBean.tarefa.projeto.nome}"/>

                        <h4>Fase</h4>
                        <h:outputText id="fase" value="#{interacaoBean.tarefa.fase.nome}"/>

                        <h4>Data de Criação</h4>
                        <h:outputText value="#{interacaoBean.tarefa.dataCriacao.time}">
                            <f:convertDateTime pattern="dd/MM/yyyy HH:mm" timeZone="#{initParam.timezone}"/>
                        </h:outputText>

                        <h4>Prazo</h4>
                        <h:outputText value="#{interacaoBean.tarefa.dataPrazo.time}">
                            <f:convertDateTime pattern="dd/MM/yyyy HH:mm" timeZone="#{initParam.timezone}"/>
                        </h:outputText>

                    </p:panelGrid>
                </p:panel>

                <p:panel header="Descrição">
                    <h:outputText id="descricao" value="#{interacaoBean.tarefa.descricao}"/>
                </p:panel>

                <p:panel header="Interações">
                <p:textEditor value="#{interacaoBean.interacao.texto}" height="300" style="margin-bottom:10px" placeholder="Nova interação..." id="textoInteracao">
                    <f:facet name="toolbar">
                         <span class="ql-formats">
                            <button class="ql-bold"></button>
                            <button class="ql-italic"></button>
                            <button class="ql-underline"></button>
                            <button class="ql-strike"></button>
                        </span>
                        <span class="ql-formats">
                            <select class="ql-font"></select>
                            <select class="ql-size"></select>
                        </span>
                    </f:facet>
                </p:textEditor>

                <p:commandButton action="#{interacaoBean.salvarInteracao}" value="Salvar" process="@form" update="textoInteracao"/>
                </p:panel>

                <p:dataTable value="#{interacaoBean.tarefa.interacoes}" var="interacao">
                    <p:column headerText="Interação">
                        <h:outputText value="#{interacao.usuario.nome}"/>
                    </p:column>
                </p:dataTable>

            </h:form>


        </ui:define>
    </ui:composition>

</html>

Eu tô tentando atualizar mesmo, porque ja to carregando a entidade com algumas informações previamente persistidas kk Essa página é específica pra adicionar informações pro campo List (interações) da tarefa.

E quanto ao CDI/Spring, acabei misturando as anotações kkkk Mas vou deixar tudo somente com spring depois

solução!

kk correto, ta agora com essa sua exception é por causa que você ta salvando a sua interação, e na sua classe interação em um objeto usuario correto? antes de salvar essa sua interação, só para teste mesmo, tenta settar esse seu usuario, algo como.

this.interacao.setUsuario(usuario); // algo parecido com isso.

Nossaaaa! Era exatamente isso! Valeu demais cara kkkk Como eu tava criando essa tela agora eu nem tinha completado ela e tava testando de acordo com o que fazia, mas nem tinha passado pela minha cabeça que essa exception poderia estar acontecendo por eu não setar um usuário. Eu setei um usuário que já existe no banco e com isso tudo correu bem!

É isso mesmo cara, faz parte isso também já passei por muitas dessas kkkk, abraços e bom estudo!