我想知道在从数据库中读取实体后是否有更好的方法来更新实体。
这似乎太多代码来完成一项简单的任务。我已经尝试使用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();
}
}
答案 0 :(得分:0)
我设法让它合并工作如下。
public void updatePodcast(Podcast podcast) {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
em.merge(podcast);
em.flush();
} finally {
em.getTransaction().commit();
em.close();
}
}