0

I've two entities and I'm using JPAContainer but I don't know how can use to do a relationship with these 2 entities.

here my code

@Entity
@Table(name="curriculum")
public class Curriculum implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long idCurriculum;

    @Temporal(TemporalType.DATE)
    private Date dataCad;

    @Size(min=5, max=50)
    @NotNull
    @NotEmpty   
    private String nome;

    @NotEmpty
    private String sexo;

    @Email
    @NotEmpty
    @NotNull
    @Size(max=250)
    @Column(unique=true)
    private String email;

    @NotNull
    @NotEmpty
    @Size(min=14, max=14)
    @Column(unique=true)
    private String cpf;
}



@Entity
@Table(name="curriculum2")
public class Curriculum2 implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long idC2; //NOT NULL AUTO_INCREMENT,

    @NotNull @OneToOne @JoinColumn(name="cpf")
    private Curriculum curriculum; //NOT NULL,

    @NotNull @Temporal(TemporalType.DATE)
    private Date dataNasceu; //NOT NULL,

    @NotNull @NotEmpty @Size(min=5, max=50)
    private String cidade; //` varchar(50) NOT NULL,

    @NotNull @NotEmpty @Size(min=5, max=50)
    private String endereco; //` varchar(50) NOT NULL,

    @NotNull 
    private int numero; //` int(11) NOT NULL,

    @NotNull @NotEmpty @Size(min=5, max=50)
    private String bairro; //` varchar(50) NOT NULL,
}


    /** here app UI */
    /** datasource */
    private final CustomJPAContainer<Curriculum2> datasource = new CustomJPAContainer<Curriculum2>(Curriculum2.class);
    private final CustomJPAContainer<Curriculum> dsCurriculum = new CustomJPAContainer<Curriculum>(Curriculum.class);

    /** beans */        
    private final Curriculum2 bean = new Curriculum2();
    private final Curriculum curriculum = dsCurriculum.getItem(22L).getEntity();

    /** beanfieldgroup validation */    
    private final BeanFieldGroup<Curriculum2> binder = new BeanFieldGroup<Curriculum2>(Curriculum2.class);


    public VerticalLayout buildLayout() {
    //mainlayout
    mainLayout = new VerticalLayout();
    mainLayout.setSpacing(true);
    mainLayout.setMargin(true);

    //tab
    tab = new TabSheet();
    tab.setSizeUndefined();
    mainLayout.addComponent(tab);

    //tab1
    vLayout_tab1 = new VerticalLayout();
    vLayout_tab1.setMargin(true);
    vLayout_tab1.setSpacing(true);

    binder.setItemDataSource(bean);
    Field<?> field = null;

    //data nascimento
    field = binder.buildAndBind("Data nascimento", "dataNasceu", PopupDateField.class);
    dataNasceu = (PopupDateField) field;
    dataNasceu.setDateFormat("dd/MM/yyyy");
    vLayout_tab1.addComponent(dataNasceu);

    //cidade 
    field = binder.buildAndBind("Cidade", "cidade", TextUpper.class);
    cidade = (TextUpper) field;
    cidade.setMaxLength(50);
    cidade.setWidth("10cm");
    vLayout_tab1.addComponent(cidade);

    //endereco
    field = binder.buildAndBind("Endereço", "endereco", TextUpper.class);
    endereco = (TextUpper) field;
    endereco.setMaxLength(50);
    endereco.setWidth("10cm");
    vLayout_tab1.addComponent(endereco);

    //numero
    field = binder.buildAndBind("Número", "numero");
    numero = (TextField) field;
    numero.setWidth("2cm");
    numero.selectAll();
    numero.addStyleName("numeros");
    vLayout_tab1.addComponent(numero);

    //bairro
    field = binder.buildAndBind("Bairro", "bairro", TextUpper.class);
    bairro = (TextUpper) field;
    bairro.setWidth("10cm");
    vLayout_tab1.addComponent(bairro);
}

/** exception */

15:53:19,600 DEBUG [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE) [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2834)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2366)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2350)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy30.executeUpdate(Unknown Source)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2870)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3381)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at org.hibernate.ejb.event.EJB3MergeEventListener.saveWithGeneratedId(EJB3MergeEventListener.java:71)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:236)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:216)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:154)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:904)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
    at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider$1.run(MutableLocalEntityProvider.java:141)
    at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.runInTransaction(MutableLocalEntityProvider.java:120)
    at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.addEntity(MutableLocalEntityProvider.java:137)
    at com.vaadin.addon.jpacontainer.provider.CachingMutableLocalEntityProvider.addEntity(CachingMutableLocalEntityProvider.java:164)
    at com.vaadin.addon.jpacontainer.JPAContainer.addEntity(JPAContainer.java:1113)
    at br.ind.ibg.views.InformacoesView.buttonClick(InformacoesView.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
    at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
    at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:969)
    at com.vaadin.ui.Button.fireClick(Button.java:368)
    at com.vaadin.ui.Button$1.click(Button.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
    at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
    at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:207)
    at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
    at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
15:53:19,602 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - SQL Error: 1452, SQLState: 23000
15:53:19,602 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
15:53:19,603 DEBUG [org.hibernate.ejb.AbstractEntityManagerImpl] - Mark transaction for rollback
15:53:19,603 DEBUG [org.hibernate.engine.transaction.spi.AbstractTransactionImpl] - rolling back
15:53:19,678 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - rolled JDBC Connection
15:53:19,679 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - re-enabling autocommit

How I can persist with JPAContainer these 2 entities ?

Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118
  • I;m not familiar with JPAContainer, but in JPA you can use one of the OneToOne, ManyToOne, ManyToMany annotations , depending on what kind of relationship you want – Svetlin Zarev Apr 30 '14 at 17:38
  • yep, in this post if you can see I'm using OneToOne at Curriculum2 ...my problem is I don't know how I do set entity Curriculum in Curriculum2 using JPAContainer...I'm trying this, but still doesn't work: binder.getItemDataSource().getBean().setCurriculum(curriculum); – FernandoPaiva Apr 30 '14 at 17:47
  • the entities Curriculum and Curriculum2 has relations. In Curriculum2 entity has a attribute " private Curriculum curriculum " that do a relation with Curriculum entity – FernandoPaiva Apr 30 '14 at 17:53
  • I guess that you set your curriculum and then commit the binder, right? Is there any exception? – nexus Apr 30 '14 at 18:46
  • @nexus I've edited the post with the exception – FernandoPaiva Apr 30 '14 at 18:56
  • Does your curriculum object you set on your bean already exist in the database? Is the cpf field of the same type as idCurriculum? In general is the foreign key properly settled? Can you add by hand/manually a row into the curriculum2 table? – nexus Apr 30 '14 at 22:20
  • @nexus yep,already exist.CPF field is a unique key in Curriculum table on database.I use this field as foreign key on table Curriculum2 and others tables because is unique.To add manually I do:Curriculum c = new Curriculum();c.setCpf("cpfnumber");Curriculum2 c2 = new Curriculum2();c2.setCurriculum(c) and execute DAO insert.With JPAContainer I don't know how to do it. – FernandoPaiva May 01 '14 at 04:31
  • @nexus I think found the problem.The CPF field in table Curriculum is unique and I'm using this field as foreign key in Curriculum2 table. I removed this foreign key and tryed add and finally added but the problem is that instead of adding the cpf added the id. Summarizing cpf doesn't add but the id add. – FernandoPaiva May 02 '14 at 13:26
  • 1
    That's true. If you are using foreign keys in JPA it uses the @Id annotation from your target entity to set the field value in the database. – nexus May 02 '14 at 15:21

1 Answers1

1

This is Hibernate 101.

For proof-of-concept this is easy. You're best bet is to use Spring transaction + hibernate + dao model

Christian Bongiorno
  • 5,150
  • 3
  • 38
  • 76