2011-07-20 57 views
1

我是JPA的新手,我的JPA有問題。 我已經使用實體管理器如下:與JPA EntityManager的問題

1: package com.icesoft.icefaces.samples.datatable.jpa; 
    2: 
    3: import java.util.logging.Level; 
    4: import java.util.logging.Logger; 
    5: 
    6: import javax.persistence.EntityManager; 
    7: import javax.persistence.EntityManagerFactory; 
    8: import javax.persistence.Persistence; 
    9: import javax.persistence.Query; 
    10: /** 
    11: * @author MyEclipse Persistence Tools 
    12: */ 
    13: public class EntityManagerHelper { 
    14:  
    15:  private static final EntityManagerFactory emf; 
    16:  private static final ThreadLocal<EntityManager> threadLocal; 
    17:  private static final Logger logger; 
    18:  
    19:  static { 
    20:   emf = Persistence.createEntityManagerFactory("tutorialPU");   
    21:   threadLocal = new ThreadLocal<EntityManager>(); 
    22:   logger = Logger.getLogger("tutorialPU"); 
    23:   logger.setLevel(Level.ALL); 
    24:  } 
    25:   
    26:  public static EntityManager getEntityManager() { 
    27:   EntityManager manager = threadLocal.get();  
    28:   if (manager == null || !manager.isOpen()) { 
    29:    manager = emf.createEntityManager(); 
    30:    threadLocal.set(manager); 
    31:   } 
    32:   return manager; 
    33:  } 
    34:  
    35:  public static void closeEntityManager() { 
    36:   EntityManager em = threadLocal.get(); 
    37:   threadLocal.set(null); 
    38:   if (em != null) em.close(); 
    39:  } 
    40:  
    41:  public static void beginTransaction() { 
    42:   getEntityManager().getTransaction().begin(); 
    43:  } 
    44:  
    45:  public static void commit() { 
    46:   getEntityManager().getTransaction().commit(); 
    47:  } 
    48:  
    49:  public static Query createQuery(String query) { 
    50:   return getEntityManager().createQuery(query); 
    51:  } 
    52:  
    53:  public static void log(String info, Level level, Throwable ex) { 
    54:   logger.log(level, info, ex); 
    55:  } 
    56:  
    57: } 

我的persistence.xml是:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> 

     <persistence-unit name="OrderEJB" type="JTA"> 
     <jta-data-source>movieDatabase</jta-data-source> 
<exclude-unlisted-classes>false</exclude-unlisted-classes> 
     </persistence-unit> 
    </persistence> 

我有兩個問題: 1 - 當我調用getEntityManager()堅持(anObject) ; 它不保存數據庫中的任何東西既不會在容器日誌中產生任何錯誤! 2,每個東西似乎確定,但是當我redploy應用(無需重新啓動服務器)JPA的每一個操作失敗,但下列情況除外:

java.lang.IllegalArgumentException: The type [null] is not the expected 
[EntityType] for the key class [class entity.MyClass]. 

,如果我重新啓動服務器,一切正常!

我使用netbeans 6.9.1,glasfish 3.1,eclipselink(JPA 2.0) 那麼我該如何解決我的問題? 由於事先

回答

0
  1. 你必須提交EntityManager的事務,這些變化將是持久的 (試行manager.getTransaction().commit()

  2. 郵政完整的堆棧跟蹤。

0

的EclipseLink的默認行爲似乎是插入查詢之前只選擇查詢完成,當你調用flush(),或在交易結束時(在提交自動沖洗)

有是具有不同行爲的持久性提供者(例如休眠)。但在你的情況嘗試調用em.flush()或關閉交易(或確保你的容器做到這一點)