2016-01-05 45 views
0

嗨,我是使用NetBeans + GlassFish的 我試圖運行此代碼: 我不作任何表創建DB(通過運行此代碼我想創建表和堅持我的對象)無法查找JNDI名稱

public static void main(String[] args) { 
    SmartphoneService ss = new SmartphoneService(); 
    Smartphone smart = new Smartphone(0, 0, null, null, null); 
    ss.create(smart); 
} 

,但我得到這個錯誤:

Unable to lookup JNDI name 

我的persistence.xml:

<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL"> 
<provider>org.hibernate.ejb.HibernatePersistence</provider> 
<jta-data-source>java:comp/env/jdbc/mysql</jta-data-source> 
<exclude-unlisted-classes>false</exclude-unlisted-classes> 
<properties> 
    <property name="javax.persistence.schema-generation.database.action" value="create"/> 
</properties> 

我的課smartphoneservice:

@Stateless 
public class SmartphoneService implements IDao<Smartphone> { 

private static final String JPQL_SELECT_PAR_ID = "SELECT u FROM Smartphone u WHERE u.idSmartphone=:id"; 

private EntityManagerFactory emf; 

private EntityManager em; 

public SmartphoneService() { 
    emf = Persistence.createEntityManagerFactory("manager1"); 
    em = emf.createEntityManager(); 
} 
public boolean create(Smartphone smart) { 
    try { 
     em.getTransaction().begin(); 
     em.persist(smart); 
     em.getTransaction().commit(); 
     return true; 

    } catch (Exception e) { 
     if (em.getTransaction() != null) { 
      em.getTransaction().rollback(); 
     } 
    } finally { 
     em.close(); 
     emf.close(); 
    } 
    return false; 
}} 

我檢查我的連接池平(平成功)

感謝烏拉圭回合的幫助

回答

1

你混了JavaSE中,並用JavaEE環境。

您的數據源看起來像是在Glassfish(Java EE環境)上配置的。所以JNDI名稱java:comp/env/jdbc/mysql只能在Java EE上下文中使用。

SmartphoneService正在運行在Java SE上下文(通過public static void main()方法。當你嘗試做的java:comp/env/jdbc/mysql查找,它不會在那裏,因爲數據源只在Glassfish的(Java EE)環境中存在。

您將需要從與註冊資源相同的上下文中執行JNDI查找。我的建議是讓您的SmartphoneService代碼在Glassfish上運行。有很多方法來驅動它 - EJB,Servlet等...

+0

我該如何解決這個問題? – FuSsA

+0

用建議的修正更新了答案 –

+0

我更新了我的問題,通過創建一個servlet ..但仍然有錯誤:/ – FuSsA