-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: How to persist a collection
PostPosted: Fri Aug 12, 2005 12:38 am 
Beginner
Beginner

Joined: Wed Mar 03, 2004 9:44 am
Posts: 23
Location: Brasil
Hello, please see my persistent classes below:
Code:
@Entity
@Table(name="Cliente")
public class Cliente {
private int id;
...
private List<Direcionamento> direcionamentos;
private List<OrdemServico> ordensServico;

    public Cliente() {
    }

    @Id
    @Column(name="IdCliente")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
...
    @OneToMany(mappedBy="cliente")
    public List<Direcionamento> getDirecionamentos() {
        return direcionamentos;
    }

    public void setDirecionamentos(List<Direcionamento> direcionamentos) {
        this.direcionamentos = direcionamentos;
    }

    @OneToMany(mappedBy="cliente")
    public List<OrdemServico> getOrdensServico() {
        return ordensServico;
    }

    public void setOrdensServico(List<OrdemServico> ordensServico) {
        this.ordensServico = ordensServico;
    }
   
}

Code:
@Entity
@Table(name="Direcionamento")
public class Direcionamento {
private int id;
private Cliente cliente;

    public Direcionamento() {
    }

    @Id
    @Column(name="IdDirecionamento")
    public int getId() {
        return id;
    }

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

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="IdCliente")
    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

}

Code:
@Entity
@Table(name="DirecionamentoProducao")
public class DirecionamentoProducao {
private int id;
private OrdemServico ordemServico;
private Direcionamento direcionamento;

    public DirecionamentoProducao() {
    }

    @Id
    @Column(name="IdDirecionamentoProducao")
    public int getId() {
        return id;
    }

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

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="IdOrdemServico")
    public OrdemServico getOrdemServico() {
        return ordemServico;
    }

    public void setOrdemServico(OrdemServico ordemServico) {
        this.ordemServico = ordemServico;
    }

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="IdDirecionamento")
    public Direcionamento getDirecionamento() {
        return direcionamento;
    }

    public void setDirecionamento(Direcionamento direcionamento) {
        this.direcionamento = direcionamento;
    }
}

Code:
@Entity
@Table(name="OrdemServico")
public class OrdemServico {
private int id;
private Cliente cliente;
private List<DirecionamentoProducao> direcionamentosProducao;

    public OrdemServico() {
    }

    @Id
    @Column(name="IdOrdemServico")
    public int getId() {
        return id;
    }

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

    @ManyToOne
    @JoinColumn(name="IdCliente")
    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    @OneToMany(mappedBy="ordemServico", cascade = CascadeType.ALL)
    public List<DirecionamentoProducao> getDirecionamentosProducao() {
        return direcionamentosProducao;
    }

    public void setDirecionamentosProducao(List<DirecionamentoProducao> direcionamentosProducao) {
        this.direcionamentosProducao = direcionamentosProducao;
    }

}


Im trying to create a collection of new DirecionamentoProducao objects each one associated with a new Direcionamento object. Next, I create a new OrdemServico object and associate it with a Client object and the collection of DirecionamentoProducao objects. My question is: How can I persist all of these objects in a unique transaction? Im using Hibernate 3.1, EntityManager 3.1 and Annotations 3.1.

[]s

Ary Junior


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 12, 2005 2:33 am 
Expert
Expert

Joined: Thu Sep 04, 2003 8:23 am
Posts: 368
Just call both client and order save methods in the same transaction.

Do you have problem with this solution ?

_________________
Seb
(Please don't forget to give credits if you found this answer useful :)


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 12, 2005 9:01 pm 
Beginner
Beginner

Joined: Wed Mar 03, 2004 9:44 am
Posts: 23
Location: Brasil
Thank you very much for your reply. Now I will explain what I'm doing. If I try:

Code:

EntityManager em = ServicoPilotoFeedBack.instancia().getEmf().createEntityManager();
ClienteDAO daoc = new ClienteDAO(em);
AgenteDAO daoa = new AgenteDAO(em);
em.getTransaction().begin();
OrdemServico os = new OrdemServico();
os.setCliente((Cliente)daoc.consulta(((ClienteListModel)cmbClientes.getModel()).getIdCliente(cmbClientes.getSelectedIndex())));
os.setAgente((Agente)daoa.consulta(((AgenteListModel)cmbAgentes.getModel()).getIdAgente(cmbAgentes.getSelectedIndex())));
List<DirecionamentoProducao> dss = (List<DirecionamentoProducao>)novosOSTableModel.getDirecionamentos();
os.setDirecionamentosProducao(dss);
em.getTransaction().commit();
em.close();



I get the exception:

Code:

Exception in thread "AWT-EventQueue-0" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [br.com.feedbackcard.piloto.modelo.DirecionamentoProducao#0]
        at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:150)
        at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
        at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:124)
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:84)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:525)
        at org.hibernate.engine.CascadingAction$8.cascade(CascadingAction.java:201)
        at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:211)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:155)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:106)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:288)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:183)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:158)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:106)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:246)
        at org.hibernate.event.def.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:124)
        at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:115)
        at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:62)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:736)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:330)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:86)
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:36)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.btnCadastraOSActionPerformed(MDIPrincipal.java:2030)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.access$3200(MDIPrincipal.java:47)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal$33.actionPerformed(MDIPrincipal.java:1803)



If I do a "merge" before the commit like this:

Code:

for (int inc = 0; inc < dss.size(); inc++) {
    dss.get(inc).setDirecionamento(em.merge(dss.get(inc).getDirecionamento()));
    dss.set(inc, em.merge(dss.get(inc)));
}



I get the exception:

Code:

Caused by: java.sql.BatchUpdateException: Column 'IdCliente' cannot be null
        at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:891)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:174)
        ... 42 more



And finally, if I try:

Code:

for (int inc = 0; inc < dss.size(); inc++) {
    dss.get(inc).getDirecionamento().setCliente(os.getCliente());
    dss.get(inc).setDirecionamento(em.merge(dss.get(inc).getDirecionamento()));
    dss.get(inc).setOrdemServico(os);
    dss.set(inc, em.merge(dss.get(inc)));
}



The OrdemServico object is saved by Hibernate. However, just one DirecionamentoProducao object and the respective Direcionamento object is saved. The remain objects in the List do'nt are saved.

[]s

Ary Junior


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 12, 2005 9:45 pm 
Beginner
Beginner

Joined: Thu Mar 31, 2005 9:58 pm
Posts: 25
Location: Valparaiso
Try this:

public Cliente() {
}

.......

@OneToMany(mappedBy="cliente", cascade=CascadeType.ALL )
public List<Direcionamento> getDirecionamentos() {
return direcionamentos;
}
.....
@OneToMany(mappedBy="cliente", cascade=CascadeType.ALL )
public List<OrdemServico> getOrdensServico() {
return ordensServico;
}



public class Direcionamento {

.....
@ManyToOne
@JoinColumn(name="IdCliente")
public Cliente getCliente() {
return cliente;
}

......
}


i.e, change the cascade type definition to the another side of the relationship

I hope this solve your problem

_________________
Daniel Casanueva R.

Jcode
Valparaiso, Chile


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 12, 2005 11:27 pm 
Beginner
Beginner

Joined: Wed Mar 03, 2004 9:44 am
Posts: 23
Location: Brasil
Hola Daniel, now only the first element of the List<DirecionamentoProducao> is saved. The Direcionamento object is OK, however, in the DirecionamentoProducao table, the fields "IdOrdemServico" and "IdDirecionamento" are setted with 0. And I get the exception:

Code:

EVERE: Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1
        at org.hibernate.jdbc.BatchingBatcher.checkRowCount(BatchingBatcher.java:92)
        at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:78)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:174)
        at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:74)
        at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:69)
        at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:150)
        at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:1959)
        at org.hibernate.persister.entity.BasicEntityPersister.updateOrInsert(BasicEntityPersister.java:1914)
        at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:2154)
        at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:84)
        at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:137)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:284)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:736)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:330)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:86)
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:36)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.btnCadastraOSActionPerformed(MDIPrincipal.java:2116)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.access$3200(MDIPrincipal.java:46)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal$33.actionPerformed(MDIPrincipal.java:1811)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
        at java.awt.Component.processMouseEvent(Component.java:5488)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
        at java.awt.Component.processEvent(Component.java:5253)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3955)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1774)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
13/08/2005 00:20:09 org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1
        at org.hibernate.jdbc.BatchingBatcher.checkRowCount(BatchingBatcher.java:92)
        at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:78)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:174)
        at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:74)
        at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:69)
        at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:150)
        at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:1959)
        at org.hibernate.persister.entity.BasicEntityPersister.updateOrInsert(BasicEntityPersister.java:1914)
        at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:2154)
        at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:84)
        at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:137)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:284)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:736)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:330)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:86)
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:36)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.btnCadastraOSActionPerformed(MDIPrincipal.java:2116)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal.access$3200(MDIPrincipal.java:46)
        at br.com.feedbackcard.piloto.visao.MDIPrincipal$33.actionPerformed(MDIPrincipal.java:1811)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
        at java.awt.Component.processMouseEvent(Component.java:5488)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
        at java.awt.Component.processEvent(Component.java:5253)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3955)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1774)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)



[]s

Ary Junior


Top
 Profile  
 
 Post subject:
PostPosted: Sat Aug 13, 2005 6:49 pm 
Beginner
Beginner

Joined: Thu Mar 31, 2005 9:58 pm
Posts: 25
Location: Valparaiso
are you asign "manually" the ids?

_________________
Daniel Casanueva R.

Jcode
Valparaiso, Chile


Top
 Profile  
 
 Post subject:
PostPosted: Sat Aug 13, 2005 9:47 pm 
Beginner
Beginner

Joined: Wed Mar 03, 2004 9:44 am
Posts: 23
Location: Brasil
No. All IDs in the DB are auto increment.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.