//-------------- 实体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>