【问题标题】:Unable to lookup JNDI name无法查找 JNDI 名称
【发布时间】:2016-04-09 21:49:57
【问题描述】:

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

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>

我的班级智能手机服务:

@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 成功)

感谢您的帮助

【问题讨论】:

    标签: jpa netbeans glassfish entitymanager


    【解决方案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 时,它不会存在,因为DataSource 仅存在于您的Glassfish 中( Java EE) 环境。

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

    【讨论】:

    • 我该如何解决这个问题?
    • 我通过创建一个 servlet 更新了我的问题..但仍然出现错误:/
    • 现在异常表明使用 jndi 名称 java:comp/env/com.fussa.test.NewServlet/ss 注入 EJB 时出现问题。我认为您应该为此打开一个单独的问题,因为您的原始问题(为什么我不能从 JavaSE 查找 JavaEE 资源)已得到解答,并且编辑您的问题会使我的原始答案无效。跨度>
    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多