This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes EJB and other Java EE Technologies and the fly likes JPA: Foreign Key Saving Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "JPA: Foreign Key Saving Problem" Watch "JPA: Foreign Key Saving Problem" New topic
Author

JPA: Foreign Key Saving Problem

Gajesh Tripathi
Greenhorn

Joined: Jul 06, 2006
Posts: 9
Dear Developers

I used netbeans: Master/Detail sample form to create Company master entry form in java
I added manually a combo box with appropriate binding for foreign key: StateId in CompanyMst which is linked with StateMst

Since this work should be done in few clicks within Netbeans, I am kinda angry at myself that I spent one and half day on it with no results... Any help?
I would be appreciate if any one help me.

I also post my problem with source at java-forums(please see):-
JPA: Foregin key saving prolem (Java-Forums)

Thanks In Advance..
gajesh
francesco umani
Greenhorn

Joined: Aug 07, 2013
Posts: 27
Please provide the code (exernal link needs authentication).
You hould code something like:

Gajesh Tripathi
Greenhorn

Joined: Jul 06, 2006
Posts: 9
Thanks francesco umani for interest in my problem...

Here is external link:-
Easy File Share Link

Thanks again...
gajesh
francesco umani
Greenhorn

Joined: Aug 07, 2013
Posts: 27
mmm

The problem is that somewhere in your code (but I can't find where) you are trying to persist an already existing Entity Statemst maybe because you are persisting a Companymst Entity that is cascading the operation on the linked Class and the error is the



You say that you are selecting a row:
Editing an Item (executing this part of code)


that do nothing, and save the item calling



where the only thing done is calling the entityManager.getTransaction().commit(). I can't figure out which operations are going to be commited at this time. Maybe having you previously pushed the addNew button, entityManager.persist(c) is the operation you're trying to commit. If so, you should try to change that in entityManager.merge(c); or try to block the cascade type from master to detail, things that I can see you have already done setting the comment on:

And by default, JPA does not cascade any persistence operations to the target of the association.

Gajesh Tripathi
Greenhorn

Joined: Jul 06, 2006
Posts: 9
Please note that I did not press "new" button because I am trying to modify the data hence entityManager.persist(c) is not called. I remove following comment as suggested by you:-
//hence commented this line
Its working and result is saved when we select a row and then click on 'save" button after modifying State using Combo Box. Same case is happened if we uncomment the following function code:-
OR If we uncomment the following code given on "save" button click:-

But only problem is that It gives error when we click on "Refresh" button and then try to save after changes...
I hope problem is in "Refresh" button code but what is it? Here is "refresh" button code:-

If you want to execute my this sample program on your system then please use attached mySQL_successionDB sql file(External Link for mySQL_succession.sql).
francesco umani
Greenhorn

Joined: Aug 07, 2013
Posts: 27
Could you provide the stack trace?
Gajesh Tripathi
Greenhorn

Joined: Jul 06, 2006
Posts: 9
NOTE:
  • Text Field of StateId is setEditable(false); I am using it for display only.
  • I also put a infomration message dialog to ensure that information is saving in database properly:-


  • After removing below Comment in CompanyMst.java (entity):

    Steps which I am using:-
  • 1. Right click on file "FrmCompanyMst.java" & then Run it.
  • 2. Click on (select) first row of masterTable {Company master}, It will display contents in Text Box & Combo Box.
  • 3. Change State using ComboBox through Mouse {from "Madhya Pradesh" to "Rajasthan"}
  • 4. Click on "Save" button & its successfully saved in database.
  • 5. Change state again: from "Madhya Pradesh" to "Punjab"
  • 6. Click on "Save" button & its again successfully saved in database.
  • {If we follow step-5 & step-6 again & again then it will save information again & again)
  • 7. Click on "Refresh" Button... It will restore information from database & we need to again select table row
  • 8. Select first row of masterTable
  • 9. Change state using comboBox(jcbStateId) from "Rajasthan" to "Madhya Pradesh" again.
  • 10. Click on "Save" button then error is occured at line: entityManager.getTransaction().commit(); & information is not saved....


  • Here is stack trace as desired {Output window text}:-
    run:
    [EL Info]: 2013-08-20 09:26:57.484--ServerSession(14120198)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
    [EL Info]: 2013-08-20 09:26:59.359--ServerSession(14120198)--file:/C:/Documents and Settings/prism/gt/projects/NumberSlider/build/classes/_BindingExamplePU login successful
    [EL Warning]: 2013-08-20 09:27:25.953--UnitOfWork(1200019)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '12' for key 'PRIMARY'
    Error Code: 1062
    Call: INSERT INTO statemst (StateId, StateName) VALUES (?, ?)
    bind => [2 parameters bound]
    Query: InsertObjectQuery(Madhya Pradesh)
    javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '12' for key 'PRIMARY'
    Error Code: 1062
    Call: INSERT INTO statemst (StateId, StateName) VALUES (?, ?)
    bind => [2 parameters bound]
    Query: InsertObjectQuery(Madhya Pradesh)

    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
    at binding.FrmCompanyMst.saveButtonActionPerformed(FrmCompanyMst.java:342)
    at binding.FrmCompanyMst.access$100(FrmCompanyMst.java:20)
    at binding.FrmCompanyMst$FormListener.actionPerformed(FrmCompanyMst.java:286)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:702)
    at java.awt.EventQueue$4.run(EventQueue.java:700)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
    Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '12' for key 'PRIMARY'
    Error Code: 1062
    Call: INSERT INTO statemst (StateId, StateName) VALUES (?, ?)
    bind => [2 parameters bound]
    Query: InsertObjectQuery(Madhya Pradesh)
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
    at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
    at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
    at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
    at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
    at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
    at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:472)
    at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
    at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
    at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:287)
    at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
    at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
    at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
    at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
    at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:224)
    at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:191)
    at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:136)
    at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1505)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:267)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1143)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:84)
    ... 40 more
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '12' for key 'PRIMARY'
    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:525)
    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:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
    ... 73 more
    francesco umani
    Greenhorn

    Joined: Aug 07, 2013
    Posts: 27
    Try to change the annotation as follow...
    Gajesh Tripathi
    Greenhorn

    Joined: Jul 06, 2006
    Posts: 9
    I made following changes in Company.java as suggested by you:-

    But it doesn't make any effect in my program... i.e. Still, Saving operation is not done after click on "Refresh" button... Same run time error is occurred.

    To run this program on your computer system, you need:-
    1. Netbeans IDE (Latest version/v7.3 is preferred) including JDK 7
    2. MySQL server {Add database: succession which is required for this very small project that has already given)

    Since this common forum hence I am giving steps to run this project after installation of Netbeans, My SQL Server & "succession" database:-
  • create new project(BindingExample) in NetBeans
  • include my provided source files{.java/.form/.xml files} to this project in "binding" package {You can also create your own Entity classes through Netbean:project node->new file->Other...->Persistence->"Entity classes from Database..."}
  • edit file: persistence.xml as per your database settings & rename persistent unit as "BindingExamplePU"

  • Gajesh Tripathi
    Greenhorn

    Joined: Jul 06, 2006
    Posts: 9
    Today, I am happy because I got solution of this problem. As I said to you, problem is with "refresh" button click hence we need to change in that code only.
    Here is solution:-

    I repeat old lines of code for click on "refresh" button here:-

    Now, just add following lines of code in this function {This is the solution}:-

    & PROBLEM IS SOLVED.

    This forum is very useful for those java professionals who wants to create a master/detail entry swing entry forms including new/delete/refresh & save button using "Netbeans Master/Detail Sample Form" feature without knowing the deep knowledge of java persistence api (JPA)

    Thanks to everyone who watch or participate in this forum & Special Thanks to "francesco uman".

    I solve this problem but I don't know actual concept behind it i.e. why refreshing of "state" entities solve this problem? If any one know then please tell me...
     
     
    subject: JPA: Foreign Key Saving Problem