简体   繁体   English

具有EclipseLink更新实体的Java SE JPA

[英]Java SE JPA with EclipseLink Update Entity

I am wondering if there is a better way to update entities after they have been read from the database. 我想知道从数据库中读取实体后是否有更好的方法来更新它们。

This seems like too much code to do a simple task. 这似乎是太多的代码,无法完成一个简单的任务。 I have tried using em.merge() which did not persists the data to the database. 我试过使用em.merge(),它不会将数据持久保存到数据库中。

public class PodcastManager {

    private EntityManagerFactory emf;


    public PodcastManager(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public void updatePodcast(Podcast podcast) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Podcast ptu = em.find(Podcast.class, podcast.getId());
        if ( ptu != null) {
            ptu.setTitle(podcast.getTitle());
            ptu.setDescription(podcast.getDescription());
            ptu.setUrl(podcast.getUrl());
            ptu.setLang(podcast.getLang());
            ptu.setCopyright(podcast.getCopyright());
            ptu.setItunesSubtitle(podcast.getItunesSubtitle());
            ptu.setItunesAuthor(podcast.getItunesAuthor());
            ptu.setItunesSummary(podcast.getItunesSummary());
            ptu.setItunesOwnerName(podcast.getItunesOwnerName());
            ptu.setItunesOwnerEmail(podcast.getItunesOwnerEmail());
            ptu.setItunesImageHREF(podcast.getItunesImageHREF());
            ptu.setExplicit(podcast.isExplicit());
        }
        em.getTransaction().commit();
        em.close();
    }
}

I managed to get it merge to work as follows. 我设法使其合并以如下方式工作。

public void updatePodcast(Podcast podcast) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(podcast);
            em.flush();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM