嗨,我正在使用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我的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成功)
谢谢你的帮助
发布于 2016-01-05 22:50:18
您正在将JavaSE和JavaEE环境混合在一起。
您的数据源看起来像是在Glassfish (Java环境)上配置的。因此,JNDI名称java:comp/env/jdbc/mysql只在Java上下文中可用。
您的SmartphoneService正在Java上下文中运行(通过public static void main()方法)。当您试图查找java:comp/env/jdbc/mysql时,它不会出现,因为DataSource只存在于您的Glassfish (Java )环境中。
您需要从注册资源的相同上下文中执行JNDI查找。我的建议是让您的SmartphoneService代码在Glassfish上运行。有很多方法来驱动它-- EJB,Servlet,等等.
https://stackoverflow.com/questions/34622390
复制相似问题