0

I tried so far the below code:

Session session = null;
Query query1 = null;
Query query2 = null;

String[] parts = userId.split("=");
userId = parts[1];
parts = userId.split(" ");
userId = parts[0];
int intIdUser = Integer.parseInt(userId);

try {
    session = getSession();

    UserCountry userCountry = new UserCountry();
    UserLanguage userLanguage = new UserLanguage();

    for (String s : user_country) {
        userCountry.setUserId(intIdUser);
        userCountry.setCountryId(Integer.parseInt(s));

        session.getTransaction().begin();
        session.persist(userCountry);
        session.getTransaction().commit();
    }

    for (String s : user_language) {
        userLanguage.setUserId(intIdUser);
        userLanguage.setLanguageId(Integer.parseInt(s));

        session.getTransaction().begin();
        session.persist(userLanguage);
        session.getTransaction().commit();
    }
}

catch(Exception e) {
    logger.error("Exception while fetching for countryId: "+userId, e);
    throw new PlRuntimeException(e.getMessage());
    }
finally {
    if(session !=null)
        session.close();
}

But the for (String s : user_country) and for (String s : user_language) loops are saving just first element on the list user_country and user_language.

How to make it save the other elements on the list?

Thanks for advice.

1 Answer 1

1

You are continuously updating the same object.

You just need to create the UserCountry and UserLanguage inside the loop. As of now you are creating outside the loop. Just move them inside the loops.

For ex :

for (String s : user_country) {
        UserCountry userCountry = new UserCountry();
        userCountry.setUserId(intIdUser);
        userCountry.setCountryId(Integer.parseInt(s));

        session.getTransaction().begin();
        session.persist(userCountry);
        session.getTransaction().commit();
    }
Sign up to request clarification or add additional context in comments.

6 Comments

This one helped! Thanks.
@SURESH ATA: Can you please provide a solution to a DELETE row solution using JPA?
it's weired, in his question, he said loops are saving just first element on the list user_country and user_language. but it should be last one if he repeats updating the same persisitent instance, isn't it?
@ROROROOROROR Since all are same. he confused :)
Yup :) Any solution os deleting rows?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.