EJB 3,實體bean使用EJB 2很大程度上是由持久化機制取代。現(xiàn)在實體Bean是一種簡單的POJO映射表。
以下是持續(xù)性的關(guān)鍵參與者的API:
2、EntityManager堅持做界面的數(shù)據(jù)操作如添加/刪除/更新/持久對象發(fā)現(xiàn)(實體)。它也有助于使用查詢接口執(zhí)行查詢。
為了演示EJB持久化機制,我們將執(zhí)行以下任務:
創(chuàng)建一個tablebooksin默認databasepostgres。
CREATE TABLE books(id integer PRIMARY KEY,name varchar(50));
//mark it entity using Entity annotation
//map table name using Table annoation@Entity@Table(name="books")publicclassBookimplementsSerializable{privateintid;privateStringname;publicBook(){}
//mark id as primary key with autogenerated value
//map database column id with id field@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="id")publicintgetId(){returnid;}...}
<?xml version="1.0"encoding="UTF-8"?><datasources><local-tx-datasource><jndi-name>PostgresDS</jndi-name><connection-url>jdbc:postgresql://localhost:5432/postgres</connection-url><driver-class>org.postgresql.driver</driver-class><user-name>sa</user-name><password>sa</password><min-pool-size>5</min-pool-size><max-pool-size>20</max-pool-size><idle-timeout-minutes>5</idle-timeout-minutes></local-tx-datasource></datasources>
<persistenceversion="1.0"xmlns="http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"><persistence-unitname="EjbComponentPU"transaction-type="JTA"><jta-data-source>java:/PostgresDS</jta-data-source><exclude-unlisted-classes>false</exclude-unlisted-classes><properties/></persistence-unit><persistence-unitname="EjbComponentPU2"transaction-type="JTA"><provider>org.hibernate.ejb.HibernatePersistence</provider><jta-data-source>java:/PostgresDS</jta-data-source><exclude-unlisted-classes>false</exclude-unlisted-classes><properties><propertyname="hibernate.hbm2ddl.auto"value="update"/></properties></persistence-unit></persistence>
@StatelesspublicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote{//pass persistence unit to entityManager.@PersistenceContext(unitName="EjbComponentPU")privateEntityManagerentityManager;publicvoidaddBook(Bookbook){entityManager.persist(book);}publicList<Book>getBooks(){returnentityManager.createQuery("From Books").getResultList();}...}
示例應用程序
Step | Description |
---|---|
1 | 在EJB - 創(chuàng)建一個Applicationchapter中解釋的packagecom。再在tutorialspoint.entity下創(chuàng)建一個名為EJB Component的項目。 您還可以使用在EJB中創(chuàng)建的項目 - 創(chuàng)建Applicationchapter,以便了解本章EJB持久性概念 |
2 | CreateBook.javaunder packagecom.tutorialspoint.entityand修改如下所示。 |
3 | CreateLibraryPersistentBean.javaandLibraryPersistentBeanRemoteas在EJB中解釋 - 創(chuàng)建Applicationchapter并修改它們?nèi)缦滤尽?/td> |
4 | Createjboss-ds.xmlinEjbComponent> setupfolder andpersistence.xmlinEjbComponent> src> conffolder。 這些文件夾可以在Netbeans中的文件選項卡中看到。 修改這些文件,如上所示。 |
5 | 清理并構(gòu)建應用程序以確保業(yè)務邏輯按照要求工作。 |
6 | 最后,在JBoss Application Server上以jar文件的形式部署應用程序。 如果JBoss應用程序服務器尚未啟動,它將自動啟動。 |
7 | 現(xiàn)在創(chuàng)建EJB客戶端,一個基于控制臺的應用程序,其方式與在EEB - 在ApplicationCreate Client下創(chuàng)建Applicationchapter以訪問EJB中說明的方式相同。 修改它如下所示。 |
packagecom.tutorialspoint.entity;importjava.io.Serializable;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.EntityListeners;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistence.Table;@Entity@Table(name="books")publicclassBookimplementsSerializable{privateintid;privateStringname;publicBook(){}@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="id")publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}}
packagecom.tutorialspoint.stateless;importcom.tutorialspoint.entity.Book;importjava.util.List;importjavax.ejb.Remote;@RemotepublicinterfaceLibraryPersistentBeanRemote{voidaddBook(BookbookName);List<Book>getBooks();}
packagecom.tutorialspoint.stateless;importcom.tutorialspoint.entity.Book;importjava.util.List;importjavax.ejb.Stateless;importjavax.persistence.EntityManager;importjavax.persistence.PersistenceContext;@StatelesspublicclassLibraryPersistentBeanimplementsLibraryPersistentBeanRemote{publicLibraryPersistentBean(){}@PersistenceContext(unitName="EjbComponentPU")privateEntityManagerentityManager;publicvoidaddBook(Bookbook){entityManager.persist(book);}publicList<Book>getBooks(){returnentityManager.createQuery("From Book").getResultList();}}
...16:30:01,401INFO[JndiSessionRegistrarBase]Bindingthe followingEntriesinGlobalJNDI:LibraryPersistentBean/remote-EJB3.xDefaultRemoteBusinessInterfaceLibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote-EJB3.xRemoteBusinessInterface16:30:02,723INFO[SessionSpecContainer]Startingjboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB316:30:02,723INFO[EJBContainer]STARTED EJB:com.tutorialspoint.stateless.LibraryPersistentBeanRemoteejbName:LibraryPersistentBean16:30:02,731INFO[JndiSessionRegistrarBase]Bindingthe followingEntriesinGlobalJNDI:LibraryPersistentBean/remote-EJB3.xDefaultRemoteBusinessInterfaceLibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote-EJB3.xRemoteBusinessInterface...
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfacesjava.naming.provider.url=localhost
packagecom.tutorialspoint.test;importcom.tutorialspoint.stateless.LibraryPersistentBeanRemote;importjava.io.BufferedReader;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.List;importjava.util.Properties;importjavax.naming.InitialContext;importjavax.naming.NamingException;publicclassEJBTester{BufferedReaderbrConsoleReader=null;Propertiesprops;InitialContextctx;{props=newProperties();try{props.load(newFileInputStream("jndi.properties"));}catch(IOExceptionex){ex.printStackTrace();}try{ctx=newInitialContext(props);}catch(NamingExceptionex){ex.printStackTrace();}brConsoleReader=newBufferedReader(newInputStreamReader(System.in));}publicstaticvoidmain(String[]args){EJBTesterejbTester=newEJBTester();ejbTester.testEntityEjb();}privatevoidshowGUI(){System.out.println("**********************");System.out.println("Welcome to Book Store");System.out.println("**********************");System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");}privatevoidtestEntityEjb(){try{intchoice=1;LibraryPersistentBeanRemotelibraryBean=LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote");while(choice!=2){StringbookName;showGUI();StringstrChoice=brConsoleReader.readLine();choice=Integer.parseInt(strChoice);if(choice==1){System.out.print("Enter book name: ");bookName=brConsoleReader.readLine();Bookbook=newBook();book.setName(bookName);libraryBean.addBook(book);}elseif(choice==2){break;}}List<Book>booksList=libraryBean.getBooks();System.out.println("Book(s) entered so far: "+booksList.size());inti=0;for(Bookbook:booksList){System.out.println((i+1)+". "+book.getName());i++;}}catch(Exceptione){System.out.println(e.getMessage());e.printStackTrace();}finally{try{if(brConsoleReader!=null){brConsoleReader.close();}}catch(IOExceptionex){System.out.println(ex.getMessage());}}}}
run:**********************WelcometoBookStore**********************Options1.AddBook2.ExitEnterChoice:1Enterbook name:LearnJava**********************WelcometoBookStore**********************Options1.AddBook2.ExitEnterChoice:2Book(s)entered so far:11.learn javaBUILD SUCCESSFUL(total time:15seconds)
run:**********************WelcometoBookStore**********************Options1.AddBook2.ExitEnterChoice:1Enterbook name:LearnSpring**********************WelcometoBookStore**********************Options1.AddBook2.ExitEnterChoice:2Book(s)entered so far:21.learn java2.LearnSpringBUILD SUCCESSFUL(total time:15seconds)
上面顯示的輸出表明,書籍存儲在持久性存儲中,并從數(shù)據(jù)庫中檢索可以到。
更多建議: