ejb加數(shù)據(jù)庫的簡單例子_第1頁
ejb加數(shù)據(jù)庫的簡單例子_第2頁
ejb加數(shù)據(jù)庫的簡單例子_第3頁
ejb加數(shù)據(jù)庫的簡單例子_第4頁
ejb加數(shù)據(jù)庫的簡單例子_第5頁
已閱讀5頁,還剩12頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

環(huán)境和那個沒有數(shù)據(jù)庫的一樣1?添加數(shù)據(jù)源文件到j(luò)boss的發(fā)布目錄中:在jboss的jboss-4.2.2.GA\docs\examples\jca目錄中找一個*-dx.xml配置數(shù)據(jù)源的文件,我用的是mysql,所以把mysql-ds.xml復(fù)制到\jboss-4.2.2.GA\server\default\deploy目錄中然后修改它:我的文件內(nèi)容如下:<?xmlversion=ll1.0"encoding=,,UTF-8,,?><!-$ld:mysql-ds.xml631752007-05-2116:26:06Zrrajesh$-><!-DatasourceconfigforMySQLusing3.0.9availablefrom:/downloads/api-jdbc-stable.html-><datasources><local-tx-datasource><jndi?name>MySqlDS</jndi?name><connection-url>jdbc:mysql://localhost:330^test</connection-url><driver-class>com?mysql?jdbc?Driver</drive「class><user-name>root</user?name〉<password>root</password><exception-sorter-class?name>org?jboss?resource?adapter?jdbc?vendor?MySQLExceptionSorter</exception?sorter?class?name><!-shouldonlybeusedondriversafter3.22.1with"ping"support<valid-connection?checker?class?name'org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection?checker?class?name〉-><!-sqltocallwhenconnectioniscreatedew-connection?sq卜somearbitrarysql</new?connectiorvsq卜-><!一sqltocallonanexistingpooledconnectionwhenitisobtainedfrompool?MySQLValidConnectionCheckerispreferredfornewerdrivers<check-valid-connection-sql>somearbitrarysql</check-valid-connection-sql>-><!一correspond!ngtype?mappinginthestandardjbosscmp-jdbc.xml-><metadata><type-mapping>mySQL</type?mapping></metadata></local-tx-datasource></datasources>2?建一個ejb工程,注意:這個要把AddsupportforEntitybeans(addJPAcapabilities)選中,J2EESpecificationLevel:選擇javaEE5.0-EJB3Z那個沒帶數(shù)據(jù)庫的也是選擇那個。

jfKuencnyectMyEdipseRunWindow旦elpr6心NewEJBProjectCreateanEJBProjectCreateanEJBprojectintheworkspaceoranexternallocation|u『E)~jsks3vinated>5tomEJBProjectDetailsProjectNameTestEjb3WithDataBaseLocationLZUsedefaultlocationDirectoryD:\workSpace\TestEjb3WithDataBaseSourcefoldersrcJ2EESpecificationLeveloJavaEE5.0?EJB3J2EE1.4?jfKuencnyectMyEdipseRunWindow旦elpr6心NewEJBProjectCreateanEJBProjectCreateanEJBprojectintheworkspaceoranexternallocation|u『E)~jsks3vinated>5tomEJBProjectDetailsProjectNameTestEjb3WithDataBaseLocationLZUsedefaultlocationDirectoryD:\workSpace\TestEjb3WithDataBaseSourcefoldersrcJ2EESpecificationLeveloJavaEE5.0?EJB3J2EE1.4?EJB2CJ2EE1.3?EJB1Browse-PersistenceConfigurationJAddsupportforEntitybeans(addJPAcapabilities)iIfpersistencesupportisnotaddednow,nopersistence.xmlfilewillbecreatedandentitybeansupportwillbeunavailable?Toaddpersistencesupportatalatertime,pleaseaddJPACapabilitiestothisproject”NewEJBProjectCreateanEJBProjectGDataSourceJNDIpathisundefinedJPAPersistencePersistenceUnitName:TestEjb3WithDataBasePUJNDIDataSource:<UseJavaTransactionAPIsDesign-timePersisteneeToolsConfigurationZSpecifyJPADatasourcedetailsDriver:CreatenewDriverCatalog/Schema:UpdateListiSelect!ngtheUpdateListbuttonrequiresthedrivertorefreshitsmetadata.ThiswillcausetheDBBrowsertoresetasitsynchronizeswithupdatedschema/cataloginformation.;sesti;sest注意:上面的JNDIDataSource:寫上:java:/MySqlDS,紅色部分是和上面的*-ds.xml的數(shù)據(jù)源

配置文件中<jndi-name>MySqlDS</jndi-name>jndi-name一樣的。接著要配置Driver,點擊后面的連接:CreatenewDriver,出現(xiàn)如下對話框:NewDatabaseConnectionDriverCreateanewconnectiondriverDrivertemplate:Drivername:ConnectionURL:Username:Password:DriverJARsDriverclassname:TestDriverjdbc:axiondb:<database?NewDatabaseConnectionDriverCreateanewconnectiondriverDrivertemplate:Drivername:ConnectionURL:Username:Password:DriverJARsDriverclassname:TestDriverjdbc:axiondb:<database?name>[:<database-directory>]ConnecttodatabaseonMyEclipsestartupSavepasswordAddJARsRemoveDrivertemplate:選擇你對于數(shù)據(jù)庫的,Drivername:隨便取個名字,中間幾項應(yīng)當不用說了,最后在DriverJARS:點擊AddJARs,添加對應(yīng)數(shù)據(jù)庫的驅(qū)動。我的配置如卞:

yirEditDatabaseConnectionDriverEdittheconnectiondriveryirEditDatabaseConnectionDriverEdittheconnectiondriverDrivertemplate:Drivername: mysqlConnectionURL:jdbc:mysql://localhost:3306/testUsername: rootPassword: ""DriverJARsE:\soft\編程軟件\mysqljar |AddJARsRemoveDriverclassname:com.mysql.jdbc.DriverTestDriver匚ConnecttodatabaseonMyEdipsestartupVISavepassword點擊finish后,回到上一個界面,點擊updatelist,然后選擇一個數(shù)據(jù)庫:我的如下:

createantJbHrojectConfigureJPApersistenceJPAPersistencePersistenceUnitName:TestEjb3WithDataBasePUJNDIDataSource: java:/MySqlDSJUseJavaTransactionAPIsDesign-timePersistenceToolsConfigurationI'ZSpecifyJPADatasourcedetailsDriver:CreatenewDriverUpdateListCatalog/Schema:iSelectingtheUpdateListbuttonrequiresthedrivertorefreshitsmetadata.ThiswillcausetheDBBrowsertoresetasitsynchronizeswithupdatedschema/cataloginformation.CreatenewDriverUpdateListCatalog/Schema:iMyEdipseJavaPersisteneeToolsusedesign-timesettingstoprovidedatabasemetadatavalidationandcontent-assist.YourJNDIdatasourceandapplicationserverconfigurationwillnotbeaffected.Tochangethesesettingsatalatertimesee:Project>Properties>MyEclipse>Persistenee點擊finish?接著配置類庫:和昨晚那個一樣步驟配置:注意多加了一個數(shù)據(jù)庫的驅(qū)動jar,我的如下:I II 八 12.在srcF建三個包org.test.modelorg.test.dao^rg.test.service.首先在org.test.model中建兩個類Customer,Orders.?代碼如下,注意其中的注解和數(shù)據(jù)庫的映射(和hibernate—*樣)。哦,還要注意那個兩個實體都要實現(xiàn)Serializable接口。Customex1?javapackageorg.test.model;importjava.io.Serializable;importjava.util.HashSet;importjava.util.Set;importjavax.persistence.CascadeType;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.FetchType;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence」d;importjavax.persistence.OneToMany;@Entity(name="customer")publicclassCustomerimplementsSerializable{*/privatestaticfinallongserialVersionlllD=7139471850142077544L;privateLongid;privateStringname;privateSet<Orders>orders=newHashSet<Orders>();@ld@GeneratedValue(strategy=GenerationType.AUTO)publicLonggetld(){returnid;}publicvoidsetld(Longid){this.id=id;}@Column(name="name",length=20,ntillable=true)publicStringgetName(){returnname;}publicvoidsetName(Stringname){this,name=name;}@OneToMany(mappedBy="customer"”cascade={CascadeType.ALL},fetchFetchType.LAZY)publicSet<Orders>getOrders(){returnorders;}publicvoidsetOrders(Set<Orders>orders){this.orders=orders;}}Orders.javapackageorg.test.model;importjava.io.Serializable;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.FetchType;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistenceJoinColumn;importjavax.persistence.ManyToOne;@Entity(name="orders1')publicclassOrdersimplementsSerializable{*/privatestaticfinallongserialVersionlllD=9110483244450845026L;privateLongid;privateStringname;privateCustomercustomer;@ld@GeneratedValue(strategy=GenerationType.AUTO)publicLonggetld(){returnid;}publicvoidsetld(Longid){this.id=id;}@Column(name="name",length=20,ntillable=true)publicStringgetName(){returnname;}publicvoidsetName(Stringname){this,name=name;}@ManyToOne(fetch=FetchType丄AZY)@JoinColumn(name=,lcutomerjd",nullable=true,unique=false,insertable=true,updatable=true)publicCustomergetCustomer(){returncustomer;}publicvoidsetCustomer(Customercustomer){this.customer=customer;3?在org.test.dao中建個接I丨CoreDAO.其中都是一些數(shù)據(jù)庫的操作(CRUD)?注意這里用了泛型定義實體和實體記。CoreDAO.javapackageorg.test.dao;importjava.io.Serializable;importjava.util.List;publicinterfaceCoreDAOcTJDextendsSerializable>{publicTfindByld(IDid);publicList<T>findAll();publicvoiddelete(Tentity);publicintdeleteAll();publicvoidsave(Tentity);publicTupdate(Tentity);publicList<T>findByProperty(StringpropertyName,finalObjectvalue,finalint..?rowStartldxAndCount);}4?建個包org.test.dao.impl.在其中建個抽象類CoreDAOImpL代碼如下:CoreDAOImpl.javapackageorg.test.dao.impl;importjava.io.Serializable;importjava.util.List;importjavax.persistence.EntityManager;importjavax.persistence.Query;importorg.test.dao.CoreDAO;publicabstractclassCoreDAOImpl<T,IDextendsSerializable>implementsCoreDAO<T,ID>{privateClass<T>entityBeanType;privateEntityManagerem;publicCoreDAOImpl(Class<T>type,EntityManagerem){this.entityBeanType=type;this.em=em;}publicCoreDAOImpl(Class<T>type){this.entityBeanType=type;}publicvoidsetEntityManager(EntityManagerem){this.em=em;}protectedEntityManagergetEntityManager(){if(em==null)thrownewHlegalStateException("EntityManager初始化異常!”);returnem;}publicClass<T>getEntityBeanType(){returnentityBeanType;}publicTfindByld(IDid){returngetEntityManager().find(getEntityBeanTypef),id);}@SuppressWarnings(Hunchecked")publicList<T>findAll(){Stringquery=''fromu+getEntityBeanType()?getName();returngetEntityManager().createQuery(query).getResultList();}publicvoiddelete(Tentity){try{getEntityManager()?remove(entity);}catch(RuntimeExceptionre){throwre;publicintdeleteAII(){intnumberDeleted=0;try{Stringname=getEntityBeanType()?getName();Queryq=em.createQuery("DELETEFROM"+name);numberDeleted=q.executeUpdate();}catch(RuntimeExceptionre){throwre;}returnnumberDeleted;}publicvoidsave(Tentity){try{getEntityManager().persist(entity);}catch(RuntimeExceptionre){throwre;}}publicTupdate(Tentity){try{Tresult=getEntityManager().merge(entity);returnresult;}catch(RuntimeExceptionre){throwre;}}@SuppressWarnings(Hunchecked")publicList<T>findByProperty(StringpropertyName,finalObjectvalue,finalint…rowStartldxAndCount){try{Stringname=getEntityBeanType()?getName();finalStringqueryString=String.format("from%swhere%s=:propertyValue1',name,propertyName);Queryquery=getEntityManager().createQuery(queryString);query.setParameter(,,propertyValue,,/value);if(rowStartIdxAndCount!=null&&rowStartldxAndCount.length>0){introwStartldx=Math.max(0zrowStartldxAndCount[0]);if(rowStartldx>0){query.setFirstResult(rowStartldx);if(rowStartldxAndCount.length>1){introwCount=Math.max(0,rowStartldxAndCount[l]);if(rowCount>0){query.setMaxResults(rowCount);}}}returnquery.getResultList();}catch(RuntimeExceptionre){throwre;}}}5?在org.test.dao中建一個接IICustomerDAO.代碼如卜CustomerDAO.javapackageorg?test?dao;importorg.test.model.Customer;publicinterfaceCustomerDAOextendsCoreDAO<CustomerzLong>{}6?在org.test.dao.impl中建一個類CustomerDAOImpL它繼承抽象的CoreDAOImpI并實現(xiàn)CustomerDAO.代碼如下:CustomerDAOImpl.javapackageorg.test.dao.impl;importjavax.persistence.EntityManager;importorg.test.dao.CustomerDAO;importorg.test.model.Customer;publicclassCustomerDAOImpIextendsCoreDAOImpl<CustomerzLong> implementsCustomerDAO{publicCustomerDAOImpl(EntityManagerem){super(Customer.classzem);7?在org.test.service中建兩個接IIServiceBeanLocaLServiceBeanRemote,代碼如下:ServiceBeanLocal.javapackageorg.test.service;importjava.util.List;importorg.test.model.Customer;publicinterfaceServiceBeanLocal{publicList<Customer>findCustomers();}ServiceBeanRemote.javapackageorg?test?service;publicinterfaceServiceBeanRemoteextendsServiceBeanLocal{}8?建一個包org.test.service.impl在其中建一個類ServiceBean并實現(xiàn)上面兩個接I1,代碼如2注意其中的注解。ServiceBean.javapackageorg.test.service.impl;importjava.util.List;importjavax.ejb.Local;importjavax.ejb.Remote;importjavax.ejb.Stateless;importjavax.persistence.EntityManager;importjavax.persistence.PersistenceContext;importjavax.persistence.PersistenceContextType;importorg.test.dao.CustomerDAO;importorg.test.dao.impl.CustomerDAOImpI;importorg.test.model.Customer;importorg.test.service.ServiceBeanLocal;importorg.test.service.ServiceBeanRemote;@Stateless(name二"service”)@Local(ServiceBeanLocal.class)@Remote(ServiceBeanRemote.class)publicclassServiceBeanimplementsServiceBeanLocal,ServiceBeanRemote{@PersistenceContext(unitName=,'TestEjb3WithDataBasePU,,/type=PersistenceContextType.TRANSACTION)privateEntityManagerem;privateCustomerDAOcustomerDAO;publicList<Customer>findCustomers(){returngetCustomerDAO().findAII();}publicCustomerDAOgetCustomerDAO(){if(this.customerDAO==null){this.customerDAO=newCustomerDAOImpl(em);}returnthis.customerDAO;}}注意:@Stateless(name=,,serviceH)中的name,它是用來改變bean發(fā)布的時候jndi的名字的,沒加name的話默認是bean的類名。@PersistenceContext()中的unitName和自動生的persistence.xml(它在src/META-INF中)中的<persistence-unit>的name一樣。9?修改配置文件persistence.xml我的文件內(nèi)容如下:<?xmlversion=,fl?0”encoding=uUTF-8,f?><persistencexmlns=Mhttp://java?sun?com/xml/ns/pe工sistence"xmlns:xsi=,'http://www?w3?org/2001/XMLSchema一instance"xsi:schemaLocation=,,http://java?sun?com/xml/ns/persistenuehttp://java?sun.com/xml/ns/persistence/persis ?xsdHversion=Hl?0”><persistence-unitname=uTestEjb3WithDataBasePUHtransaction-typG="<provider>org?hibernate?ejb?HibernatePe工sistenceC/provider〉<jta-data-source〉java:/MySqlDS</jta-data-source><class>org?test?model?Customer</class><class>org?test?model?Orders</class><properties><propertyname=Mhibernate?dialect1'value=uorg.hibernate?

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論