繁体   English   中英

Java EE-通过Glassfish资源将EJB连接到Oracle数据库

[英]Java EE - Connect EJB to Oracle Database through Glassfish resource

我特别是Java和EE的新手。 我开始了一个EE项目,该项目应该提供REST API,它将处理远程Oracle数据库中的2个实体。 我使用NetBeans是因为它是在Enterprise Java中完成任何事情的唯一方法(正如我现在所看到的)。

我所做的:

  1. 我在Glassfish(v4.1-13)中创建了JDBC池。 我可以成功ping通池。 然后,我为该池创建了JDBC资源。
  2. 我为需要处理的两个实体生成了Entity类。

 <persistence version="2.1" xmlns...> <persistence-unit name="semestralka-ejbPU" transaction-type="JTA"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <jta-data-source>jdbc/dbs</jta-data-source> <class>cz.ctu.bitjv.kopecj24.semestralka.entities.Food</class> <class>cz.ctu.bitjv.kopecj24.semestralka.entities.User</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> <properties> <property name="eclipselink.target-database" value="Oracle"/> </properties> </persistence-unit> </persistence> 

  1. 我有一个无状态EJB,它像这样调用实体管理器:

 public FoodServiceBean() { this.facade = new FoodFacade(Food.class); this.facade.setEntityManager(Persistence.createEntityManagerFactory("semestralka-ejbPU").createEntityManager()); } 

  1. 然后,有一个REST服务类应列出数据库中的实体。

    @Path(“ food”)公共类FoodResource {

     @Context private UriInfo context; private FoodServiceInterface service; /** * Creates a new instance of FoodResource */ public FoodResource() { try { InitialContext ic = new InitialContext(); service = (FoodServiceInterface) ic.lookup("java:global/semestralka/semestralka-ejb/FoodServiceBean"); } catch (NamingException ex) {...} } @GET @Produces(MediaType.TEXT_PLAIN) @Path("list") public String getAll() { List<Food> foods = service.listAllFood(); ... } 

    }

不幸的是,一旦我请求getAll操作(访问localhost:8080 / semestralka-war / wr / food / list),我将收到此异常:

Warning:   StandardWrapperValve[cz.ctu.bitjv.kopecj24.semestralka.rest.ApplicationConfig]: Servlet.service() for servlet cz.ctu.bitjv.kopecj24.semestralka.rest.ApplicationConfig threw exception
javax.naming.NameNotFoundException: dbs not found

这是异常屏幕的屏幕截图: Glassfish 500错误屏幕

仔细检查持久性单元和glassfish服务器中的连接池名称。 您也可以使用实体来更新您的问题。

我可以看到您从休息服务拨打的ejb是错误的。 您需要添加带有程序包路径的远程接口名称。

假设您的软件包路径为com.rs.www,那么您的查找字符串应为以下字符串:

 service = (FoodServiceInterface) ic.lookup("java:global/semestralka/semestralka-ejb/FoodServiceBean!com.rs.www.FoodServiceInterface");

谢谢。

最后,我找到了解决方案。 问题出在我的FoodServiceBean中。 我试图实例化EJB构造函数中的Facade,但是EntityManager被注入到构造函数之后。 所以这里是Bean的代码,可以帮助我解决问题。

@Stateless
@EJB(beanInterface=FoodServiceInterface.class, name="FoodServiceBean")
public class FoodServiceBean implements FoodServiceInterface {    

@PersistenceContext(unitName="testPU")
private EntityManager em;

private FoodFacade facade;

public FoodServiceBean()
{

}

@PostConstruct
public void init() {
    this.facade = new FoodFacade(Food.class);
    this.facade.setEntityManager(em);
}

请注意,我更改了持久性单元的名称只是为了确保没有错别字。

谢谢您的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM