//-------------- 實體bean 的開發
////------配置 jboss 的數據源
--給出一個 oralce的配置? oracle-ds.xml
添加JPA的持久化配置文件 persistence.xml 類是 hibernate
jndi.properties
---編寫 實體bean
采用注解 配置 ORM 映射關系
BiAnswer.java
BiAnswerService.java
BiAnswerServiceBean.java
BiAnswerServiceTest.java
--使用 Ant 進行編譯
build.xml
1:實體bean 屬于Java持久化規范 (簡稱JPA)里的技術,實體bean通過元數據在javabean和數據庫表之間建立映射關系,然后java程序員就可以隨性所欲 使用面向對象的編程思想來操作數據了. 2:JPA的出現主要是為了簡化現有的持久化開發工作和整合ORM技術. 3:目前實現了JPA規范過的主流產品有Hibernate TopLink OpenJPA ibatis mybatis . 4:在 jboss中采用HIbernate 最為其持久化實現產品.

////------配置 jboss 的數據源
1.數據庫連接對象的創建是很耗性能的,配置數據源后可以提升性能.. jboss5.0 和 jboss 6.0 一樣 EBJ 提供了模版啦!! E:\jboss-5.0.0.GA\docs\examples\jca 里面就可以看到很多數據的配置模版 比如mysql 的配置模版 mysql-ds.xml 然后修改 比如 <jndi-name>MySqlDS</jndi-name> <connection-url>jdbc:mysql://mysql-hostname:3306/jbossdb</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>x</user-name> <password>y</password> 第一個:修改 jndi名稱 第二個Ip地址: localhost:3306 第三個數據名稱: jbossdb---> spdb1 (創建數據庫的時候一般使用 UTF-8編碼) 第四個用戶名:x--->root 第五個密碼y:123456 注意: 數據源的文件的取名:必須要以 -ds 結尾 發布之前 還要注意 "數據庫的驅動類" 復制到 E:\jboss-5.0.0.GA\server\default\lib 完成后 將修改好的 mysql-ds.xml 拷貝到 E:\jboss-5.0.0.GA\server\default\deploy 此時就會看到 數據源的jndi名稱為: java:MySqlDS 到jboss控制后臺 查看 數據源 http://localhost:8080/jmx-console/ --->jboss.jca---name:java:MySqlDS; 然后要注意的一個 就是 查看數據源一些屬性的配置 查看 連接池的 屬性 點擊進去 name=JbossOracleDS,service=ManagedConnectionPool MaxSize :最大可以數量 默認 20 條 InUseConnectionCount :正在使用的連接統計. MinSize :最小的連接數量 BlockingTimeoutMillis:最大等待時間 30秒 修改后 點擊 Apply Changes 只用在jboss 運行時候就生效 關閉 就會丟失修改后的值 要永久的修改 就要修改數據源文件 mysql-ds.xml 添加參數 <min-pool-size>1</min-pool-size> <min-pool-size>50</min-pool-size> 注意 正在使用人數 和 數據源的最大連接數 如果數量 一直是滿的 就要考慮 是否擴大連接數了
--給出一個 oralce的配置? oracle-ds.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- ===================================================================== --> <!-- --> <!-- JBoss Server Configuration --> <!-- --> <!-- ===================================================================== --> <!-- $Id: oracle-ds.xml 23720 2004-09-15 14:37:40Z loubyansky $ --> <!-- ==================================================================== --> <!-- Datasource config for Oracle originally from Steven Coy --> <!-- ==================================================================== --> <datasources> <local-tx-datasource> <jndi-name>JbossOracleDS</jndi-name> <connection-url>jdbc:oracle:thin:@192.168.1.242:1521:ora11g</connection-url> <!-- Here are a couple of the possible OCI configurations. For more information, see http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/java.920/a96654/toc.htm <connection-url>jdbc:oracle:oci:@youroracle-tns-name</connection-url> or <connection-url>jdbc:oracle:oci:@(description=(address=(host=youroraclehost)(protocol=tcp)(port=1521))(connect_data=(SERVICE_NAME=yourservicename)))</connection-url> Clearly, its better to have TNS set up properly. --> <driver-class>oracle.jdbc.driver.OracleDriver</driver-class> <user-name>bjdata</user-name> <password>bjdata</password> <!-- Uses the pingDatabase method to check a connection is still valid before handing it out from the pool --> <!--valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker</valid-connection-checker-class-name--> <!-- Checks the Oracle error codes and messages for fatal errors --> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name> <!-- sql to call when connection is created <new-connection-sql>some arbitrary sql</new-connection-sql> --> <!-- sql to call on an existing pooled connection when it is obtained from pool - the OracleValidConnectionChecker is prefered <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql> --> <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) --> <metadata> <type-mapping>Oracle10g</type-mapping> </metadata> </local-tx-datasource> </datasources>
添加JPA的持久化配置文件 persistence.xml 類是 hibernate
<!--根據JPA的規范的要求,在實體bean的應用中,我們需要在應用的類路徑下的META-INF目錄加入持久化配置文件 persistence.xml--> <?xml version="1.0" encoding="UTF-8"?> <persistence 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" version="1.0"> <!-- 持久化單元 (可以配置多個) JTA: 全局事物 ejb默認的事務類型 可以不用設置 RESOURCE_LOCAL:本地事務 添加數據源 :提高性能 --> <persistence-unit name="mytest" transaction-type="JTA" > <!-- 配置的jboss 數據源jndi名稱 --> <jta-data-source>java:JbossOracleDS</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/> <!-- 自動生存表接口 create-drop:啟動創建表,程序 卸載的時候會刪除表結構 測試的有用 create:啟動創建, 卸載的時候不會刪除 update:保留數據庫的數據,如果添加新的字段后,會同步到數據庫中. <property name="hibernate.hbm2ddl.auto" value="create-drop"/> --> <!-- 打印 sql語句 --> <property name="hibernate.show_sql" value="true"/> <!--格式化sql語句 --> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>
jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.provider.url=localhost:1099
---編寫 實體bean
采用注解 配置 ORM 映射關系
BiAnswer.java
package com.sh.ejb3.bean; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity //@Entity(name="xxx") 可以修改 @Table(name="bi_answer") public class BiAnswer implements Serializable{ private static final long serialVersionUID = 5687494436224059560L; private Integer id; @Column(name="answer",length=300,nullable=true) private String answer; private String correct; private Integer sortid; private Integer qid; private Date createtime; public BiAnswer() { } public BiAnswer(Integer id,String answer,Integer qid) { this.id=id; this.answer=answer; this.qid=qid; } @Id @Column(name="id") //這些注解 只能標注在 get() 方法上 不能在set 上 還可以標注 字段上 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @Column(name="correct",length=1,nullable=true) public String getCorrect() { return correct; } public void setCorrect(String correct) { this.correct = correct; } @Column(name="sortid",length=10,nullable=true) public Integer getSortid() { return sortid; } public void setSortid(Integer sortid) { this.sortid = sortid; } @Column(name="qid",length=10,nullable=true) public Integer getQid() { return qid; } public void setQid(Integer qid) { this.qid = qid; } @Column(name="createtime",nullable=true) public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BiAnswer other = (BiAnswer) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
BiAnswerService.java
package com.sh.ejb3.service; import java.util.List; import com.sh.ejb3.bean.BiAnswer; public interface BiAnswerService { public void save (BiAnswer answer); public void update(BiAnswer answer); public void delete(Integer answerid); public BiAnswer getAnswer(Integer answerid); public List<BiAnswer> getAnswers(); }
BiAnswerServiceBean.java
package com.sh.ejb3.service.impl; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import com.sh.ejb3.bean.BiAnswer; import com.sh.ejb3.service.BiAnswerService; @Stateless @Remote(BiAnswerService.class) public class BiAnswerServiceBean implements BiAnswerService { //使用實體管理器 如果只有一個 持久化單元 unitName可以不用配置 否則有多個的話 就需要配置 @PersistenceContext(unitName="mytest") EntityManager em; @Override public void save(BiAnswer answer) { // TODO Auto-generated method stub em.persist(answer); //只將持久化字段保存到數據庫中對應的字段 } @Override public void update(BiAnswer answer) { // TODO Auto-generated method stub em.merge(answer); //answer 為 游離狀態 而且 進行了修改 使用 merge } @Override public void delete(Integer answerid) { // TODO Auto-generated method stub //getReference 返回的是一個 代理對象 一般都是 懶加載 和 Hibernate中 一樣 em.remove(em.getReference(BiAnswer.class, answerid)); //處于托管狀態 } @Override public BiAnswer getAnswer(Integer answerid) { // TODO Auto-generated method stub return em.find(BiAnswer.class, answerid); //如果沒有找到就返回一個null } @SuppressWarnings("unchecked") //終止警告 @Override public List<BiAnswer> getAnswers() { // TODO Auto-generated method stub //注意 采用的 HQL 語句 注意 BiAnswer 的類的簡單名稱 可以通過 @Entity(name="xxx") 修改 return em.createQuery("SELECT o from BiAnswer o").getResultList(); } }
BiAnswerServiceTest.java
package junit.test; import static org.junit.Assert.fail; import java.util.List; import javax.naming.InitialContext; import org.junit.BeforeClass; import org.junit.Test; import com.sh.ejb3.bean.BiAnswer; import com.sh.ejb3.service.BiAnswerService; public class BiAnswerServiceTest { private static BiAnswerService answerService; @BeforeClass public static void setUpBeforeClass() throws Exception { try { //不采用硬編碼 就可以直接 添加 一個jndi.properties 會自動從java類路徑中 去尋找 服務器的配置文件 InitialContext ctx=new InitialContext();//InitialContext(props); answerService=(BiAnswerService)ctx.lookup("BiAnswerServiceBean/remote"); //測試 遠程接口 } catch (Exception e) { e.printStackTrace(); } } @Test public void testSave() { answerService.save(new BiAnswer(1050,"5等南瓜多少分?",1040)); } @Test public void testUpdate() { BiAnswer answer=answerService.getAnswer(1048); answer.setAnswer("家園被污染了!!嗚嗚"); answerService.update(answer); } }
--使用 Ant 進行編譯
build.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- ====================================================================== 2013-2-25 下午1:53:33 project description Bin ====================================================================== --> <project name="EntityBean" basedir="."> <description> description </description> <!-- 設置項目原目錄 --> <property name="src.dir" value="${basedir}\src" /> <!-- 獲取環境變量 --> <property environment="env"/> <property name="jboss.home" value="${env.JBOSS_HOME}"/> <property name="jboss.server.config" value="default"/> <property name="build.dir" value="${basedir}\build"/> <!-- 引入 jboss client 下的 所有jar --> <path id="build.classpath"> <fileset dir="${jboss.home}\client"> <include name="*.jar"/> </fileset> <!-- 講編譯過后的路徑加入到 path中去 方便 接口和實現的引用 --> <pathelement location="${build.dir}"/> </path> <target name="prepare" description="創建build目錄"> <delete dir="${build.dir}"/> <mkdir dir="${build.dir}"/> </target> <!-- - - - - - - - - - - - - - - - - - target: compile - - - - - - - - - - - - - - - - - --> <target name="compile" depends="prepare" description="編譯"> <javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false" includes="com/**"> <classpath refid="build.classpath"/> </javac> </target> <!-- ================================= target: ejbjar ================================= --> <target name="ejbjar" depends="compile" description="創建EJB發布包"> <jar jarfile="${basedir}\${ant.project.name}.jar"> <fileset dir="${build.dir}"> <include name="**/*.class"/> </fileset> <!-- 將原目錄下META-INF下的所有文件都打包到 jar文件的META-INF下--> <metainf dir="${src.dir}\META-INF"></metainf> </jar> </target> <!-- ================================= target: deploy ================================= --> <target name="deploy" depends="ejbjar" description="發布EJB"> <copy file="${basedir}\${ant.project.name}.jar" todir="${jboss.home}\server\${jboss.server.config}\deploy"/> </target> <!-- - - - - - - - - - - - - - - - - - target: undeploy - - - - - - - - - - - - - - - - - --> <target name="undeploy" description="卸載EJB"> <delete file="${jboss.home}\server\${jboss.server.config}\deploy\${ant.project.name}.jar"/> </target> </project>
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
