无法查找 JNDI 名称

Unable to lookup JNDI name

您好,我正在使用 netbeans+glassfish 我正在尝试 运行 此代码: 我只创建没有任何 table 的数据库(通过 运行 宁此代码我想创建 tables 并保留我的对象)

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>

我的 class 智能手机服务:

@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;
}}

我检查了我的连接池 ping(Ping 成功)

感谢您的帮助

您混淆了 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 ,它不会存在,因为 DataSource 仅存在于您的 Glassfish (Java EE) 环境中。

您需要从注册资源的同一上下文执行 JNDI 查找。我的建议是在 Glassfish 上制作您的 SmartphoneService 代码 运行。有很多方法可以驱动它——EJB、Servlet 等...