Selectevent autocomplete returns null object

Asked

Viewed 112 times

0

I’m using the autocomplete and when I enter a field, it alone fills two other fields with the method handleSelect(SelectEvent event). But these two objects of these fields are getting null when recording. I debugged and saw that they are filled, but when saving they are null. And in stacktrace shows that the attribute aluno_id is null and cannot persist, that Student is just one of the tables that will be persisted when recording.

The autocomplete

<p:outputLabel value="Título da Monografia: " for="tituloMonografia" />
                <p:autoComplete id="tituloMonografia" size="100"
                    value="#{gestaoBancaDefesaBean.bancaDefesa.monografia}"
                    completeMethod="#{gestaoBancaDefesaBean.completarMonografia}"
                    var="monografia" itemLabel="#{monografia.titulo}"
                    itemValue="#{monografia}" forceSelection="true" groupBy="titulo" >
                    <o:converter converterId="omnifaces.ListConverter" list="#{gestaoBancaDefesaBean.listaMonografias}" />
                    <p:ajax event="itemSelect"
                        listener="#{gestaoBancaDefesaBean.handleSelect}"
                        update="aluno" />
                    <p:ajax event="itemSelect"
                        listener="#{gestaoBancaDefesaBean.handleSelect}" update="orientador" />
                </p:autoComplete>

EDIT

The Student Form part, the entity that is having trouble persisting

<p:outputLabel value="Aluno: " for="aluno" />
                <p:autoComplete id="aluno" size="40"
                    value="#{gestaoBancaDefesaBean.bancaDefesa.monografia.aluno}"                   
                    converter="omnifaces.SelectItemsConverter" var="aluno"
                    itemLabel="#{aluno.pessoa.nome}" itemValue="#{aluno}">
                </p:autoComplete>

The method handleSelect

 public void handleSelect(SelectEvent event) {

    this.monografia = (Monografia) event.getObject();

}
abr 01, 2018 7:04:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1048, SQLState: 23000
abr 01, 2018 7:04:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Column 'aluno_id' cannot be null
abr 01, 2018 7:04:21 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
javax.el.ELException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.apache.el.parser.AstValue.invoke(AstValue.java:260)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:150)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:96)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:839)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:870)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1418)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    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:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    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:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)


 Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:875)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:844)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:849)
    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.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at org.jboss.weldx.persistence.EntityManager$2128648003$Proxy$_$$_WeldClientProxy.merge(Unknown Source)
    at com.daniel.monografia.repository.BancaDefesas.guardar(BancaDefesas.java:48)
    at com.daniel.monografia.service.CadastroBancaDefesaService.salvar(CadastroBancaDefesaService.java:21)
    at com.daniel.monografia.service.CadastroBancaDefesaService$Proxy$_$$_WeldSubclass.salvar$$super(Unknown Source)
    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.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:49)
    at org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:77)
    at com.daniel.monografia.util.TransacionalInterceptor.invoke(TransacionalInterceptor.java:42)
    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.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:73)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
    at com.daniel.monografia.service.CadastroBancaDefesaService$Proxy$_$$_WeldSubclass.salvar(Unknown Source)
    at com.daniel.monografia.controller.GestaoBancaDefesaBean.salvar(GestaoBancaDefesaBean.java:96)
    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:247)
    ... 35 more
**Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement**
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2840)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3411)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:623)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:277)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:258)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:303)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.jpa.event.internal.core.JpaMergeEventListener.saveWithGeneratedId(JpaMergeEventListener.java:56)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:255)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:235)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:173)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:863)
    ... 71 more
**Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'aluno_id' cannot be null**
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 90 more

The Bean

@Named
@ViewScoped
public class GestaoBancaDefesaBean implements Serializable {

private static final long serialVersionUID = 1L;

@Inject
private BancaDefesas bancaDefesas;

@Inject
private Professores professores;

@Inject
private Monografias monografias;

@Inject
private FacesMessages messages;

@Inject
private CadastroBancaDefesaService cadastroBancaDefesaService;

private Converter monografiaConverter;

private List<BancaDefesa> listaBancaDefesas;

private List<Professor> listaProfessores;

private List<Monografia> listaMonografias;

private String termoPesquisa;

private BancaDefesa bancaDefesa;

private Aluno aluno;

private Professor professor;

private Monografia monografia;

public void handleSelect(SelectEvent event) {

    this.monografia = (Monografia) event.getObject();

}

@PostConstruct
private void iniciar() {

    bancaDefesa = new BancaDefesa();
    this.bancaDefesa.setMonografia(new Monografia());

    aluno = new Aluno();
    this.aluno.setPessoa(new Pessoa());

    professor = new Professor();
    this.professor.setPessoa(new Pessoa());

    listaProfessores = professores.todos();

    listaMonografias = monografias.todas();
}

public void prepararNovaBanca() {
    //bancaDefesa = new BancaDefesa();
    //this.bancaDefesa.setMonografia(new Monografia());
}

public void prepararEdicao() {

}

public void salvar() {
    cadastroBancaDefesaService.salvar(bancaDefesa);

    atualizarRegistros();

    messages.info("Banca salva com sucesso!");

    RequestContext.getCurrentInstance().update(Arrays.asList("frm:bancaDefesasDataTable", "frm:messages"));
}

public void pesquisar() {
    listaBancaDefesas = bancaDefesas.pesquisar(termoPesquisa);

    if (listaBancaDefesas.isEmpty()) {
        messages.info("Sua consulta não retornou registros.");
    }
}

public void todasBancaDefesas() {
    listaBancaDefesas = bancaDefesas.todas();
}

public List<Monografia> completarMonografia(String termo) {
    List<Monografia> listaMonografias = monografias.pesquisar(termo);

 monografiaConverter = new MonografiaConverter(listaMonografias);

    return listaMonografias;
 }

private void atualizarRegistros() {
    if (jaHouvePesquisa()) {
        pesquisar();
    } else {
        todasBancaDefesas();
    }
}

private boolean jaHouvePesquisa() {
    return termoPesquisa != null && !"".equals(termoPesquisa);
}

public String getTermoPesquisa() {
    return termoPesquisa;
}

public void setTermoPesquisa(String termoPesquisa) {
    this.termoPesquisa = termoPesquisa;
}

public List<BancaDefesa> getListaBancaDefesas() {
    return listaBancaDefesas;
}

public void setListaBancaDefesas(List<BancaDefesa> listaBancaDefesas) {
    this.listaBancaDefesas = listaBancaDefesas;
}

public List<Professor> getListaProfessores() {
    return listaProfessores;
}

public void setListaProfessores(List<Professor> listaProfessores) {
    this.listaProfessores = listaProfessores;
}

public List<Monografia> getListaMonografias() {
    return listaMonografias;
}

public void setListaMonografias(List<Monografia> listaMonografias) {
    this.listaMonografias = listaMonografias;
}

public BancaDefesa getBancaDefesa() {
    return bancaDefesa;
}

public void setBancaDefesa(BancaDefesa bancaDefesa) {
    this.bancaDefesa = bancaDefesa;
}

public Monografia getMonografia() {
    return monografia;
}

public void setMonografia(Monografia monografia) {
    this.monografia = monografia;
}

public Converter getMonografiaConverter() {
    return monografiaConverter;
}

public boolean isBancaDefesaSeleciona() {
    return bancaDefesa != null && bancaDefesa.getId() != null;
 }
}

The entity making the persistence BancaDefesa.java

@Entity
@Table(name="banca_defesa")
public class BancaDefesa implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Future
@Temporal(TemporalType.DATE)
@Column(name = "data_defesa")
private Date dataDefesa;

private String local;

private boolean defendida;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "aluno_id")
private Aluno aluno;

@ManyToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
@JoinTable(name="bancadefesa_professor", joinColumns=
{@JoinColumn(name="banca_defesa_id")}, inverseJoinColumns=
{@JoinColumn(name="professor_id")})
private List <Professor> listaProfessores;

@NotNull
@OneToOne(cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, fetch=FetchType.EAGER)
@JoinColumn(name = "monografia_id")
private Monografia monografia;

@Transient
private Professor professor;

public Long getId() {
    return id;
}

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

public boolean isDefendida() {
    return defendida;
}

public void setDefendida(boolean defendida) {
    this.defendida = defendida;
}

public String getLocal() {
    return local;
}

public void setLocal(String local) {
    this.local = local;
}

public Date getDataDefesa() {
    return dataDefesa;
}

public void setDataDefesa(Date dataDefesa) {
    this.dataDefesa = dataDefesa;
}

public Aluno getAluno() {
    return aluno;
}

public void setAluno(Aluno aluno) {
    this.aluno = aluno;
}

public List<Professor> getListaProfessores() {
    return listaProfessores;
}

public void setListaProfessores(List<Professor> listaProfessores) {
    this.listaProfessores = listaProfessores;
}

public Monografia getMonografia() {
    return monografia;
}

public void setMonografia(Monografia monografia) {
    this.monografia = monografia;
}

public Professor getProfessor() {
    return professor;
}

public void setProfessor(Professor professor) {
    this.professor = professor;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    BancaDefesa other = (BancaDefesa) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

@Override
public String toString() {
    return "BancaDefesa [id=" + id + "]";
}

}

1 answer

0

Looking at the stacktrace of your problem it was possible to observe that the entity Aluno is referenced in the entity BancaDefesas. Since you have not included the classes referring to your back-end, I believe your problem lies in trying to persist the entity BancaDefesas which refers to an object Aluno that has not yet been persisted, as shown by that stretch of your stacktrace:

Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
...
at com.daniel.monografia.repository.BancaDefesas.guardar(BancaDefesas.java:48)
at com.daniel.monografia.service.CadastroBancaDefesaService.salvar(CadastroBancaDefesaService.java:21)
at com.daniel.monografia.service.CadastroBancaDefesaService$Proxy$_$$_WeldSubclass.salvar$$super(Unknown Source)

One of the solutions to this scenario would be to persist the entity Aluno before the entity persists BancaDefesas. As you are using Hibernate in your project, it would be good to take a look at Annotation CascadeType of the framework in question.

  • I’ll take a look and tell you the result

  • I posted the Bean and the Entity that are used in persistence. I already use the annotation CascadeType, so I guess it’s not the problem. dataDefesa is receiving the object monografia, receiving the object aluno, receiving the object pessoa, who receives the attribute nome value="#{gestaoBancaDefesaBean.bancaDefesa.monografia.aluno}" &#xA; converter="omnifaces.SelectItemsConverter" var="aluno"&#xA; itemLabel="#{aluno.pessoa.nome}" itemValue="#{aluno}"

  • 1

    See that there is reference both to Monografia as to Aluno in its class mapping BancaDefesa and in the code excerpt that you included above, is made the instantiation of the student in the object Monografia. Maybe the table banca_defesa is not accepting a value null in the column aluno_id. Do this check and post the result. If in doubt, post the table structure banca_defesa.

  • From what I understand, am I missing in the relationship? That’s what you said is right, the table BancaDefesa has the fields aluno_id and professor_id, as in the table Monograph

  • That’s what you said, you were relating aluno and professor both with the table monografia, so much with the bancadefesa. I left the relationship only in monografia and managed to record the data. Sorry for the silly question of beginner, thank you very much, helped me in my TCC.

  • If you have solved your problem with the information in the answer, you can accept it.

  • But as your first answer was not the solution but the other comment you answered here, how do I do? Or I can create a response and mark as a solution?

  • If the answer is in the reply comments, you can accept it.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.