无法查找JNDI名称



嗨,我用的是netbeans+glassfish我正在尝试运行以下代码:我只创建没有任何表的DB(通过运行此代码,我想创建表并持久化我的对象)

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

my 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>

我的班级智能手机服务:

@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(JavaEE环境)上配置的。因此JNDI名称java:comp/env/jdbc/mysql将仅在JavaEE上下文中可用。

您的SmartphoneService正在Java SE上下文中运行(通过public static void main()方法)。当您尝试查找java:comp/env/jdbc/mysql时,它不会出现,因为DataSource只存在于Glassfish(Java EE)环境中。

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

最新更新