Associação 1:N (Hibernate, Srping, JSF, MySQL)

2 respostas
dgrava

Boa Tarde pessoal!

Tenho uma associação 1:N que está feita dessa forma no banco de dados:

CREATE TABLE `usuarioteste` (

  `id` int(11) unsigned NOT NULL auto_increment,

  `nome` varchar(50) default NULL,

  `apelido` varchar(15) default NULL,

  PRIMARY KEY  (`id`)

) ENGINE=InnoDB;

 

e 

 

CREATE TABLE `telefonesusuarioteste` (

  `id` int(11) unsigned NOT NULL auto_increment,

  `telefone` int(11) default NULL,

  `idusuario` int(11) unsigned NOT NULL,

  PRIMARY KEY  (`id`),

  KEY `Usuario_FKIndex1` (`idusuario`)

) ENGINE=InnoDB;

Meus beans estão assim:

public class Usuarioteste  implements java.io.Serializable {

 
     private int id;

     private String nome;

     private String apelido;

     private Set telefonesusuariotestes = new HashSet();

 

// getters and setters

 

e

 

public class Telefonesusuarioteste  implements java.io.Serializable {

 
     private int id;

     private Usuarioteste usuarioteste;

     private Integer telefone;

     private Integer idusuario;

 

// getters and setters

Meus hbm.xml estão dessa forma:

Usuarioteste.hbm.xml

 

<hibernate-mapping>

    <class name="br.com.artfesta.beans.Usuarioteste" table="usuarioteste" catalog="artfesta">

        <id name="id" type="int">

            <column name="id" />

            <generator class="assigned" />

        </id>

        

        <property name="nome" type="string">

            <column name="nome" length="50" />

        </property>

        <property name="apelido" type="string">

            <column name="apelido" length="15" />

        </property>

        

        <set name="telefonesusuariotestes" 

             inverse="true" 

             lazy="true"

             cascade="all-delete-orphan">

            

            <key column="idusuario" />

            <one-to-many class="br.com.artfesta.beans.Telefonesusuarioteste" />

        </set>

    </class>

</hibernate-mapping>

 

e

 

Telefonesusuarioteste.hbm.xml

 

<hibernate-mapping>

    <class name="br.com.artfesta.beans.Telefonesusuarioteste" table="telefonesusuarioteste" catalog="artfesta">

        <id name="id" type="int">

            <column name="id" />

            <generator class="assigned" />

        </id>

        

        <property name="telefone" type="java.lang.Integer">

            <column name="telefone" />

        </property>

        

        <many-to-one name="usuarioteste" 

                         class="br.com.artfesta.beans.Usuarioteste" 

                         column ="idusuario" >

        </many-to-one>

        

        

    </class>

</hibernate-mapping>

Eu estou tentando salvar assim ( adaptando de exemplos que peguei na internet à forma que faço… uso HibernateDaoSupport):

public void salvarOuAlterarUsuarios(Usuarioteste usuarioteste, Telefonesusuarioteste teluteste) {
		try {
			
			getSession().beginTransaction();			
					
			usuarioteste.setTelefonesusuariotestes(new HashSet());
			usuarioteste.getTelefonesusuariotestes().add(teluteste);
			
			getSession().saveOrUpdate(usuarioteste);
			
			getSession().getTransaction().commit();
			
			getSession().close();
			
		} catch (HibernateException e) {
			throw convertHibernateAccessException(e);
		}
		
	}

Mas quando corro o método, ele salva a tabela Usuarioteste os dados preenchidos mas não salva nada na tabela Telefonesusuarioteste e me retorna esse stack com o seguinte erro:

Hibernate: select telefonesu_.id, telefonesu_.telefone as telefone7_, telefonesu_.idusuario as idusuario7_ from artfesta.telefonesusuarioteste telefonesu_ where telefonesu_.id=?

Hibernate: insert into artfesta.usuarioteste (nome, apelido, id) values (?, ?, ?)

Hibernate: insert into artfesta.telefonesusuarioteste (telefone, idusuario, id) values (?, ?, ?)

06/12/2006 18:06:51 org.hibernate.util.JDBCExceptionReporter logExceptions

WARNING: SQL Error: 1048, SQLState: 23000

06/12/2006 18:06:51 org.hibernate.util.JDBCExceptionReporter logExceptions

SEVERE: Column 'idusuario' cannot be null

06/12/2006 18:06:51 org.hibernate.event.def.AbstractFlushingEventListener performExecutions

SEVERE: Could not synchronize database state with session

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

      at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)

      at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)

      at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:202)

      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)

      at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)

      at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:297)

      at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)

      at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:985)

      at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:333)

      at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)

      at br.com.artfesta.DAO.Impl.ImplUsuariotesteDAO.salvarOuAlterarUsuarios(ImplUsuariotesteDAO.java:45)

      at br.com.artfesta.negocios.GerenciadorUsuarioteste.criarOuAlterarUsuarioteste(GerenciadorUsuarioteste.java:45)

      at br.com.artfesta.negocios.GerenciadorUsuarioteste$$FastClassByCGLIB$$2f53536e.invoke(<generated>)

      at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)

      at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:709)

      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:148)

      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:100)

      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:170)

      at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:647)

      at br.com.artfesta.negocios.GerenciadorUsuarioteste$$EnhancerByCGLIB$$95616348.criarOuAlterarUsuarioteste(<generated>)

      at br.com.artfesta.jsf.backing.UsuariotesteManaged.salvarOuAlterarUsuario(UsuariotesteManaged.java:82)

      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

      at java.lang.reflect.Method.invoke(Method.java:585)

      at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:126)

      at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:72)

      at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:211)

      at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:267)

      at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:381)

      at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:75)

      at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)

      at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)

      at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)

      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)

      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

      at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._invokeDoFilter(AdfFacesFilterImpl.java:367)

      at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._doFilterImpl(AdfFacesFilterImpl.java:336)

      at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl.doFilter(AdfFacesFilterImpl.java:196)

      at oracle.adf.view.faces.webapp.AdfFacesFilter.doFilter(AdfFacesFilter.java:87)

      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

      at org.apache.myfaces.component.html.util.ExtensionsFilter.doFilter(ExtensionsFilter.java:122)

      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)

      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)

      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)

      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)

      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)

      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)

      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)

      at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)

      at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)

      at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)

      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)

      at java.lang.Thread.run(Thread.java:595)

Caused by: java.sql.BatchUpdateException: Column 'idusuario' cannot be null

      at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665)

      at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)

      at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)

      ... 54 more

Alguém aí sabe onde eu estou errando ??

Vi que é alguma coisa com o campo idusuario da tabela Telefonesusuarioteste não poder ser null mas não to conseguindo enxergar como resolver…

Obrigado

Douglas

2 Respostas

alberto_ribeiro

Então dgrava pelo que eu conheço de Hibernate, quando você tem um relacionamento 1:N você apenas faria isso:

na sua classe UsuarioTeste teria a lista de telefonesusuariotestes…(do mesmo jeito que você já tem)

private Set telefonesusuariotestes = new HashSet();

e na classe Telefonesusuarioteste você não precisa colocar:

private Usuarioteste usuarioteste;

tem como você postar o código que você seta os usuários e os telefones propriedade por propriedade ???

[]'s

alberto_ribeiro

cara analisando outro aspecto tb encontrei isso no seu código que pra mim acho que é o problema:

usuarioteste.setTelefonesusuariotestes(new HashSet());

ai vc está dando um new e criando um hashset todo vazio sem nada dentro e quando você faz save ele deve estar tentando salvar o relacionamento e como está vazio ele da erro…

TENTE ASSIM:

public void salvarOuAlterarUsuarios(Usuarioteste usuarioteste, Telefonesusuarioteste teluteste) {
try {		
getSession().beginTransaction();	
usuarioteste.add(teluteste);
getSession().saveOrUpdate(usuarioteste);
getSession().getTransaction().commit();
getSession().close();
 			
 		} catch (HibernateException e) {
 			throw convertHibernateAccessException(e);
 		}
 		
 	}

[]'s

Criado 7 de dezembro de 2006
Ultima resposta 7 de dez. de 2006
Respostas 2
Participantes 2