Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 195789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:42:43+00:00 2026-05-11T16:42:43+00:00

I am using JPA with Hibernate underneath, and I am having trouble getting merge

  • 0

I am using JPA with Hibernate underneath, and I am having trouble getting merge to work,
but before I describe the problems I am encountering with JPA, let me lay out what I am trying to accomplish, just in case my problems stems from my approach.

I have data from on system that I need to place into another system. To do this I am reading the data then constructing new ORM objects based on that data, I then want to persist the ORM objects into the database. Now when the database is empty, the program works without issue, with a simple em.persist(object) call. However I want to be able to run this process when the database has data in it, adding new data and updating old data as necessary, this is where I am having issues.

I do a simple check to see if the item already exists in the database, if nothing is found, I persist, if the record exists, I attempt a merge. Which fails with a duplicate record error;

ERROR JDBCExceptionReporter - Violation of UNIQUE KEY constraint 'UK-SubStuff-StuffId-SubStuffNumber'. Cannot insert duplicate key in object 'SubStuff'.

It strikes me as strange that the em.merge() call is attempting a insert instead of a update (I confirmed this through SQL logging).

Hibernate: insert into SubStuff (SubStuffNumber, StuffId, Name, TypeId) values (?, ?, ?, ?)

I should note that I am using objects that cascade into sub-objects. The failure is occurring on a sub-object, which makes sense to me as I would expect it to try and merge the sub-objects first.

Below is my code, please excuse the rough state, I’ve tried to document a few workaround approaches here.

private void storeData(Collection<Stuff> Stuffs) {

    for (Stuff stuff : Stuffs) {
        //I think this first block can be safely ignored, as I am having no issues with it
        //  Left it in just in case someone more experianced then I sees the root of the issue here.
        Collection<SubStuff> subStuffs = stuff.getSubStuffCollection();
        for (SubStuff s : subStuffs) {
            //Persist SubStuff Type, which DOES NOT cascade,
            //  due to it not having an internal SubStuff collection
            Query q = em.createNamedQuery("SubStuffType.findByType");
            q.setParameter("type", f.getTypeId().getType());
            try {
                SubStuffType sst = (SubStuffType) q.getSingleResult();
                s.setTypeId(sst);
            } catch (NoResultException ex) {
                if (logger.isDebugEnabled()) logger.debug("SubStuff Type not found, persisting");
                em.persist(s.getTypeId());
            }
        }

        if (em.find(Stuff.class, stuff.getId()) == null) {
            //Persist on Stuffs will cascade to SubStuffs
            em.persist(stuff);
        } else {
            //  Failing to merge SubStuff, tries to insert duplicate
            //  Merge SubStuff first
            // The block below is my attempt to merge the SubStuff Collection before merging Stuff,
            //  it creates the same isuse as a straight merge of Stuff.
            Collection<SubStuff> mergedSubStuffs = new ArrayList<SubStuff>(SubStuffs.size());
            for (SubStuff s : SubStuffs) {
                Query q = em.createNamedQuery("SubStuff.findBySubStuffNumberStuffId");
                q.setParameter("SubStuffNumber", s.getSubStuffNumber());
                q.setParameter("StuffId", stuff.getId());
                try {
                    SubStuff subStuff = (SubStuff) q.getSingleResult();
        // -----> Merge fails, with an duplicate insert error
                    SubStuff mergedSubStuff = em.merge(s);
                    mergedSubStuffs.add(mergedSubStuff);
                } catch (NoResultException ex) {
                    throw ex;
                }
            }
            stuff.setSubStuffCollection(mergedSubStuffs);

        // -----> This will fails with same error as above, if I remove the attempt
            //  to merge the sub objects
            em.merge(stuff);
        }
    }
}

If anyone with JPA experience can help me out I would really appreciate it. The differances between Hibernate’s saveOrUpdate() and JPA’s merge() are obviously tripping me up, but despite reading several articles on EnityManger’s merge, I still can’t wrap my head around what is going on here.

Thanks for your time.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:42:43+00:00Added an answer on May 11, 2026 at 4:42 pm

    The curse of StackOverflow has struck again. After working on this problem for about a day I decide to post this question, within 20 minutes I had an eureka moment and solved it. Partly because I had clarified my thoughts enough to post the question. In thinking about what information might be pertinent to the question I realized that my auto generated keys were to blame (or my correctly, my stupid non-handling of them on a merge).

    My issue is that SubStuff (worst substitute naming scheme, sorry about that) has an autogenerated artificial primary key. So when merging I needed to do;

    SubStuff subStuff = (SubStuff) q.getSingleResult();
    //++++++++
    s.setId(subStuff.getId());
    //++++++++
    
    //The following code can be removed.
    //--- SubStuff mergedSubStuff = em.merge(f);
    //--- mergedSubStuffs.add(mergedSubStuff);
    

    This sets the primary key to the row that already exists in the database and upon initial testing seems to work fine.

    The call to merge can be simplified down to just the call to em.merge(stuff) as that will cascade the substuff objects and the mergedsubstuff collection can be removed all together as we are no longer doing a merge inside that loop.

    Thanks to anyone who read through my ridiculously long question, hopefully my question will be useful to someone in the future.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using Hibernate's JPA impl to model some tables. I'm having trouble mapping a
I'm using JPA 2 with Hibernate 3.6.8 as the implementation. Let's say we have
I have a JPA using Hibernate connected to SQLserver. It works but i have
I'm having difficulty using the CITEXT datatype in PostgreSQL using JPA and Hibernate. CITEXT
JPA/Hibernate missing column I am using JPA with Hibernate as the provider. I had
I'm using the Hibernate JPA 2 Metamodel Generator to generate metamodel classes for my
I'm using Hibernate and JPA for a small project. Somehow when trying to obtain
I'm using Hibernate with JPA and MySQL. I got accessing denied. java.sql.SQLException: Access denied
I am using Ejb3 and JPA (based on Hibernate and Oracle 10g at the
I'm seeing strange behaviour when using PostgreSQL in a Hibernate/JPA environment with a single

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.