[RESOLVIDO]JPA result returns more than one elements

Boa tarde, tenho um problema, tenho uma aplicação que estou começando a desenvolver com JSF 2.0 e JSA 2.0,

Vamos ao problema, tenho 2 entidades mapeadas many to many, consigo persistir, update e remover na boa, quando
eu uso um método de busca, ele funciona na boa mas, quando eu atualizo trocando a disciplina ele gera esse erro.

desde já muito obrigado.

stack trace

javax.persistence.NonUniqueResultException: result returns more than one elements
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:287)
at br.com.universidade.repositorio.CursoRepositorio.listIdD(CursoRepositorio.java:121)
at br.com.universidade.mb.CursoBean.buscar(CursoBean.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
29/12/2010 16:46:09 com.sun.faces.application.ActionListenerImpl processAction
SEVERE: java.lang.NullPointerException
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at br.com.universidade.mb.CursoBean.buscar(CursoBean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
… 23 more
29/12/2010 16:46:09 com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{cursoBean.buscar}: java.lang.NullPointerException
javax.faces.FacesException: #{cursoBean.buscar}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:114)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
… 22 more
Caused by: java.lang.NullPointerException
at br.com.universidade.mb.CursoBean.buscar(CursoBean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
… 23 more
29/12/2010 16:46:09 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/universidade] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at br.com.universidade.mb.CursoBean.buscar(CursoBean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

ENTIDADES

CURSO


package br.com.universidade.entidades;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@NamedQueries({ 
	@NamedQuery(name = "getCurso.Discplina", query = "select c from Curso c inner join fetch c.disciplinas where c.nome like ?1"), 
	@NamedQuery(name="getCurso.Prepara",query="select c from Curso c inner join fetch c.disciplinas where c.idCurso=?1")

})

@Entity
public class Curso {

	@Id
	@GeneratedValue
	private Long idCurso;

	private String nome;

	private String descricao;

	private int duracao;

	@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.REMOVE })
	@JoinTable(name = "curso_disciplina", joinColumns = { @JoinColumn(name = "idCurso") }, inverseJoinColumns = { @JoinColumn(name = "idDisciplina") })
	private Set<Disciplina> disciplinas;

	public Set<Disciplina> getDisciplinas() {
		return disciplinas;
	}

	public void setDisciplinas(Set<Disciplina> disciplinas) {
		this.disciplinas = disciplinas;
	}

	public Long getIdCurso() {
		return idCurso;
	}

	public void setIdCurso(Long idCurso) {
		this.idCurso = idCurso;
	}

	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 int getDuracao() {
		return duracao;
	}

	public void setDuracao(int duracao) {
		this.duracao = duracao;
	}

}

DISCIPLINA


package br.com.universidade.entidades;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@NamedQueries({ @NamedQuery(name = "getDisciplina", query = "select d from Disciplina d inner join fetch d.cursos") })
@Entity
public class Disciplina {

	@Id
	@GeneratedValue
	private Long idDisciplina;

	private String nome;

	@ManyToMany(fetch = FetchType.EAGER, cascade = {
			CascadeType.MERGE,CascadeType.REMOVE })
	@JoinTable(name = "curso_disciplina", joinColumns = { @JoinColumn(name = "idDisciplina") }, inverseJoinColumns = { @JoinColumn(name = "idCurso") })
	private Set<Curso> cursos;

	public Set<Curso> getCursos() {
		return cursos;
	}

	public void setCursos(Set<Curso> cursos) {
		this.cursos = cursos;
	}

	public Long getIdDisciplina() {
		return idDisciplina;
	}

	public void setIdDisciplina(Long idDisciplina) {
		this.idDisciplina = idDisciplina;
	}

	public String getNome() {
		return nome;
	}

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

}

REPOSITÒRIOS


package br.com.universidade.repositorio;

import java.util.List;


import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import br.com.universidade.DAO.DAO;
import br.com.universidade.entidades.Curso;
import br.com.universidade.entidades.Disciplina;

import br.com.universidade.util.JPAUtil;

public class CursoRepositorio implements DAO<Curso> {

	Curso curso = new Curso();

	public void adciona(Curso curso) {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			em.persist(curso);
			em.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			em.getTransaction().rollback();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Curso> list() {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			Query query = em.createQuery("from Curso");
			em.getTransaction().commit();
			return query.getResultList();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;

	}


	public void remove(Curso curso) {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			curso = em.merge(curso);
			em.remove(curso);
			em.getTransaction().commit();

		} catch (Exception ex) {
			ex.printStackTrace();
			em.getTransaction().rollback();

		} finally {
			em.close();
		}
	}

	public void update(Curso curso) {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			em.flush();
			em.merge(curso);
			em.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			em.getTransaction().rollback();
		}

	}
	
	public Curso listParametro(String nome, Long idD) {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();

		try {

			Query query = em.createNamedQuery("getCurso.Discplina")
					.setParameter(1, nome + "%");

			return (Curso) query.getSingleResult();

		} catch (NoResultException ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public Curso listNomeID(String nome, Long idD) throws NonUniqueResultException {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			Query query = em.createNamedQuery("getCurso.Prepara");
            //query.setParameter(1,idD);
			
			return (Curso) query.getSingleResult();
		} catch (NoResultException e) {
			curso = null;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return null;

	}
	
	public Disciplina listIdD(Long IdD) throws NonUniqueResultException {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			Query query = em.createNamedQuery("getDisciplina");
            
			
			return  (Disciplina) query.getSingleResult();
		} catch (NoResultException e) {
			curso = null;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return null;
		

	}

}

MANAGE BEAN

package br.com.universidade.mb;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import br.com.universidade.entidades.Curso;
import br.com.universidade.entidades.Disciplina;
import br.com.universidade.repositorio.CursoRepositorio;

@ManagedBean
public class CursoBean {

	private Curso curso = new Curso();

	private List<Curso> cursos;
	@SuppressWarnings("rawtypes")
	private DataModel listacurso;

	private Disciplina disciplinas = new Disciplina();
	private List<Disciplina> listDisci = new ArrayList<Disciplina>();

	CursoRepositorio repositorio = new CursoRepositorio();

	public String adciona() {
		CursoRepositorio repositorio = new CursoRepositorio();
		Set<Disciplina> armazena = new HashSet<Disciplina>();
		armazena.add(disciplinas);
		curso.setDisciplinas(armazena);
		repositorio.adciona(curso);
		return "index";
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public DataModel getListaCurso() {
		cursos = repositorio.list();
		listacurso = new ListDataModel(cursos);
		return listacurso;
	}

	public String excluirCurso() {
		Curso cursotemp = (Curso) (listacurso.getRowData());
		repositorio.remove(cursotemp);
		return "index";
	}

	public String buscar() {

		CursoRepositorio repositorio = new CursoRepositorio();
		
		this.disciplinas = repositorio.listIdD(this.disciplinas.getIdDisciplina());

		this.curso = repositorio.listParametro(this.curso.getNome(),
				this.disciplinas.getIdDisciplina());

		
		return "pesquisacurso";
	}

	public String preparAlterarCurso() {

		CursoRepositorio repositorio = new CursoRepositorio();
		repositorio.listIdD(this.disciplinas.getIdDisciplina());
		this.curso = repositorio.listNomeID(this.curso.getNome(),
				this.disciplinas.getIdDisciplina());
		return "pesquisacurso";

	}

	public String atualiza() {
		CursoRepositorio repositorio = new CursoRepositorio();
		Set<Disciplina> armazena = new HashSet<Disciplina>();
		armazena.add(disciplinas);
		curso.setDisciplinas(armazena);
		repositorio.update(curso);
		return "index";
	}

	public Disciplina getDisciplinas() {
		return disciplinas;
	}

	public void setDisciplinas(Disciplina disciplinas) {
		this.disciplinas = disciplinas;
	}

	public Curso getCurso() {
		return curso;
	}

	public void setCurso(Curso curso) {
		this.curso = curso;
	}

	public List<Curso> getCursos() {
		return cursos;
	}

	public void setListcurso(List<Curso> cursos) {
		this.cursos = cursos;
	}

	public List<Disciplina> getListDisci() {
		return listDisci;
	}

	public void setListDisci(List<Disciplina> listDisci) {
		this.listDisci = listDisci;
	}

	

}

Olá.

Esse erro ocorre pq vc esperou receber um objeto,mas o método retornou uma coleção de objetos.

Vc tem uma solução porque eu tentei colocar método List listIdD(Long IdD) com return query.getResultList mas o parametro vem nulo tem como me ajudar.

Resolvi :


	public String buscar() {

		CursoRepositorio repositorio = new CursoRepositorio();
		
		this.disciplinas = repositorio.listIdD(this.disciplinas.getIdDisciplina(),this.curso.getNome());

		this.curso = repositorio.listParametro(this.curso.getNome(),
				this.disciplinas.getIdDisciplina());

		
		return "pesquisacurso";
	}

Repositório

	public Curso listParametro(String nome, Long idD) {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();

		try {

			Query query = em.createNamedQuery("getCurso.Discplina")
					.setParameter(1, nome + "%");

			return (Curso) query.getSingleResult();

		} catch (NoResultException ex) {
			ex.printStackTrace();
			return null;
		}
	}
public Disciplina listIdD(Long IdD,String nomeC) throws NonUniqueResultException {
		EntityManager em = (EntityManager) JPAUtil.getInstance()
				.createEntityManager();
		try {
			Query query = em.createNamedQuery("getDisciplina").
			setParameter(1, nomeC + "%");
			
            
			
			return  (Disciplina) query.getSingleResult();
		} catch (NoResultException e) {
			curso = null;
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return null;
		

	}

JPQL