下面接着总结Ejb使用会话Bean+实体bean+数据源开发流程:
先新建一个Java项目导入\jboss-4.2.3.GA\client
第一步:配置数据源
在\jboss-4.2.3.GA\docs\examples\jca目录下mssql-ds.xml(数据源配置文件)
配置内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: mysql-ds.xml 71535 2008-04-01 07:05:03Z
[email protected] $ -->
<!-- Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->
<datasources>
<local-tx-datasource>
<jndi-name>liyongMySql</jndi-name><!--JNDI名称在persistence.xml文件中配置--->
<connection-url>jdbc:mysql://localhost:3306/entitydatabse?useUnicode=true&characterEncoding=UTF-8</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password>liyong</password>
<min-pool-size>3</min-pool-size>
<max-pool-size>100</max-pool-size>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<!-- should only be used on drivers after 3.22.1 with "ping" support
<valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-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 - MySQLValidConnectionChecker is preferred for newer drivers
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->
<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
然后将这个数据源配置文件copy到jboss-4.2.3.GA\server\default\deploy进行发布
第二步:
在src目录下新建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">
<!-- 以transaction-type下是 事务提交类型有两种事务:第一、本地事务(在同一个数据库中完成事务) 第二、全局事务(在不同数据库中需要在同一事务中完成不同数据库的操作)-->
<persistence-unit name="person" transaction-type="JTA"><!-- EJB使用全局事务 -->
<!---在数据源中配在的数据源JNDI名称-->
<jta-data-source>java:liyongMySql</jta-data-source>
<properties>
<!-- 显示最终执行的SQL -->
<property name="hibernate.show_sql" value="true"/>
<!-- 格式化显示的SQL -->
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
第三步:编写实体bean Persion.java
package com.liyong.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Persion implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
public Persion(){}
public Persion(String name) {
this.name=name;
}
@Id @GeneratedValue//默认为auto
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=20)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@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;
Persion other = (Persion) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
第四步:编写一个会话bean PersionService.java和接口IPersionService.java
接口:
public interface IPersionService {
public void save(Persion persion);
public Persion getPersion(Integer persionid);
public List<Persion> getAllPersions();
public void update(Persion persion);
public void delete(Persion persion);
}
实现类:
package com.liyong.service;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.liyong.bean.Persion;
@Stateless
@Remote(IPersionService.class)
public class PersionService implements IPersionService{
@PersistenceContext(unitName="person") EntityManager manager;
public void delete(Persion persion) {
manager.remove(persion);
}
@SuppressWarnings("unchecked")
public List<Persion> getAllPersions() {
return manager.createQuery("select o from Persion o").getResultList();
}
public Persion getPersion(Integer persionid) {
return manager.find(Persion.class, persionid);
}
public void save(Persion persion) {
manager.persist(persion);
}
public void update(Persion persion) {
manager.merge(persion);
}
}
第五步:编写一个单元测试PersionTest.java
package junit.test;
import java.util.List;
import javax.naming.InitialContext;
import org.junit.BeforeClass;
import org.junit.Test;
import com.liyong.bean.Persion;
import com.liyong.service.IPersionService;
public class PersionTest {
private static IPersionService persionService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
InitialContext ctx = new InitialContext();
persionService = (IPersionService) ctx.lookup("PersionService/remote");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testSave(){
try {
Persion persion=new Persion("ly");
persionService.save(persion);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testGetPersoin(){
System.out.println(persionService.getPersion(1).getName());
}
@Test
public void testUpdate(){
Persion persion=persionService.getPersion(1);
persion.setName("xxxx");
persionService.update(persion);
}
@Test
public void testGetAllPersions(){
List<Persion> persions=persionService.getAllPersions();
for(Persion persion:persions){
System.out.println(persion.getName());
}
}
}
对了还需要一个jndi.properties(这个可以参考前面HelloWord)
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=localhost\:1099
我们使用build.xml来打包编译
<?xml version="1.0"?>
<!-- ======================================================================= -->
<!-- EJB3 HelloWorld build file -->
<!-- ======================================================================= -->
<project name="EjbEntityBean" default="ejbjar" basedir="..">
<property environment="env" />
<property name="app.dir" value="${basedir}\EjbEntityBean" /><!--EjbEntityBean是项目名称-->
<property name="src.dir" value="${app.dir}\src" />
<property name="jboss.home" value="${env.JBOSS_HOME}" />
<property name="jboss.server.config" value="default" />
<property name="build.dir" value="${app.dir}\build" />
<property name="build.classes.dir" value="${build.dir}\classes" />
<!-- Build classpath -->
<path id="build.classpath">
<fileset dir="${jboss.home}\client">
<include name="*.jar" />
</fileset>
<pathelement location="${build.classes.dir}" />
</path>
<!-- =================================================================== -->
<!-- Prepares the build directory -->
<!-- =================================================================== -->
<target name="prepare" depends="clean">
<mkdir dir="${build.dir}" />
<mkdir dir="${build.classes.dir}" />
</target>
<!-- =================================================================== -->
<!-- Compiles the source code -->
<!-- =================================================================== -->
<target name="compile" depends="prepare" description="编绎">
<!--includes筛选哪些包下的类被编译-->
<javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" optimize="off" includes="com/**">
<classpath refid="build.classpath" />
</javac>
</target>
<target name="ejbjar" depends="compile" description="创建EJB发布包">
<jar jarfile="${app.dir}\EjbEntityBean.jar">
<fileset dir="${build.classes.dir}">
<include name="com/**/*.class" />
</fileset>
<!--包含这个persistence.xml文件-->
<metainf dir="${src.dir}\META-INF"></metainf>
</jar>
</target>
<target name="deploy" depends="ejbjar">
<copy file="${app.dir}\EjbEntityBean.jar" todir="${jboss.home}\server\${jboss.server.config}\deploy" />
</target>
<!-- =================================================================== -->
<!-- Cleans up generated stuff -->
<!-- =================================================================== -->
<target name="clean">
<delete dir="${build.dir}" />
<delete file="${jboss.home}\server\${jboss.server.config}\deploy\HelloWorld.jar" />
</target>
</project>