[英]Java EE - Connect EJB to Oracle Database through Glassfish resource
我特別是Java和EE的新手。 我開始了一個EE項目,該項目應該提供REST API,它將處理遠程Oracle數據庫中的2個實體。 我使用NetBeans是因為它是在Enterprise Java中完成任何事情的唯一方法(正如我現在所看到的)。
我所做的:
<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>
public FoodServiceBean() { this.facade = new FoodFacade(Food.class); this.facade.setEntityManager(Persistence.createEntityManagerFactory("semestralka-ejbPU").createEntityManager()); }
然后,有一個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服務器中的連接池名稱。 您也可以使用實體來更新您的問題。
我可以看到您從休息服務撥打的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.