Search code examples
jpaentity

Entity Manager fails on merging from JSON when @GeneratedValue is set


I am currently working on a Servlet which saves songs. I am using hsqldb with JPA and my problem is that on initializing the DB I have to load 10 songs from a JSON file. But as long as I use @GeneratedValue in my song Entity it will just load 5 of the 10 songs.

Here is my code where I access the JSON file.

 @Override
public void init() {
    emf = Persistence.createEntityManagerFactory("NewPersistenceUnit");

    // Problem with loading just half the json
    loadSongsFromJSON("songs.json");
    System.out.println("DB initialized");
}

private void loadSongsFromJSON(String filename) {
    List<Song> songsFromJSON = null;
    EntityManager em = null;
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        InputStream is = getClass().getClassLoader().getResourceAsStream(filename);
        songsFromJSON = objectMapper.readValue(is, new TypeReference<List<Song>>() {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (songsFromJSON != null) {

        //for testing
        System.out.println("ALL SONGS IN INIT" + System.lineSeparator());

        for (Song s : songsFromJSON) {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            //em.persist(s);
            em.merge(s);

            //for testing
            System.out.println("ADDED " + s);

            em.getTransaction().commit();
            em.close();
        }
    }
}

All 10 Songs are definitly in the list since:

System.out.println("ADDED " + s);

is printing out all of them.

I also need to use @GeneratedValue so deleting it isn't an option.


Solution

  • Ok I solved the problem. Tomislav's answer helped me solving it.

    The problem was, that in my JSON the songs have a set ID. So I set all ID's to null and then persisted them normally with

    s.setId(null);
    em.persist(s) //instead of em.merge(s)