日志文章

2008年03月10日 21:19:06

EJB3.0 step by step<course 1>

Wangwj/scttsc
Valenwon/cnoug
参考资料:oreilly ejb3.0
2008-03-10
本文介绍如何建立你的JAVAEE环境和第一个EJB demo
“Spring已经成了当今J2EE企业应用的事实标准,我记得去年某期的程序员杂志有这么一句话。不可否认spring的普及程度,但也不能忽视EJB这个官方标准。据我所知,很多大牌厂商的电信解决方案里(包括HP/IBM/Oracle),依然是基于J2EE/EJB这个备受批评的框架,而且做J2EE的人谁又没用过MDB呢,做接口,做分布式应用,做集群,你还得靠EJB
所需软件,eclipse3.2jboss-4.2.2.GAOracle10gjdk5.0
OS: win xp pro EN
软件的获取方法,除开eclipse以外,其它两个都在各自官方网下载。这里不做介绍。需要注意的是jboss4.2.2开始默认支持EJB3
本次实验,依靠ant来进行编译和部署,其它步骤手工进行,并未使用其它插件来生成任何文件。
需要你有ant使用的基本经验,和对persistence等概念的了解。
Okay,here we go.
Step1.配置环境

Java环境配置略。
Jboss需设定JBOSS_HOME,本例为D:\jboss-4.2.2.GA
Oracle测试schema中建立测试表aps2.test_employee
-- Create table
create table test_employee
(
id   number,
name   varchar2(
20),
age   integer,
address varchar2(
200)
);
-- Create/Recreate primary, unique and foreign key constraints
alter table test_employee
add constraint pk_test_employee primary key (ID);
配置JBOSS使用Oracle数据源

找到D:\jboss-4.2.2.GA\docs\examples\jca\oracle-ds.xml文件,复制一个新的文件后,将他改名为aps65-ds.xml(aps65为本例的schema简称)。编辑该文件,需修改的部门如下:

连接串

<connection-url>jdbc:oracle:thin:@133.37.61.65:1521:aps2</connection-url>

用户名

<user-name>***</user-name>

密码

<password>***</password>

...
拷贝到D:\jboss-4.2.2.GA\server\default\deploy
这样就完成本例的配置,实际JBOSS配置数据源还有更多要点,在这里暂不作说明,仅为运行当前例子。

Step2.目录结构

新建一个java项目名称EJB41,引用D:\jboss-4.2.2.GA\server\default\lib所有jar,和D:\jboss-4.2.2.GA\lib下面所有jar
新建立一个sourcefoldersrc。其余目录结构如下:
Ejb41
---src   源文件目录
---build 编译后文件目录
---resources
---META-INF
  persistence.xml 持久化配置文件

---client-config
jndi.properties

log4j.xml

---build.xml

Step3.java源码

建立一个entity bean,注意它的annotation@Entity@Table,它告诉容器这是一个数据库映射类。
package com.titan.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;

@Entity
@Table(name="TEST_EMPLOYEE")

public class Test_employee {
private int id;
private String name;
private int age;
private String address;
@Id
@Column(name="ID")
public int getId()
{
return id;
}
public void setId(int pk)
{
id = pk;
}
@Column(name="NAME")
public String getName()
{
  return name;
}
public void setName(String str)
{
name = str;
}
@Column(name="AGE")
public int getAge()
{
return age;
}
public void setAge(int ag)
{
age = ag;
}
@Column(name="ADDRESS")
public String getAddress()
{
  return address;
}
public void setAddress(String addr)
{
address = addr;
}
}
Java persistence要求一个persistence.xmlXML部署描述文件,里面是一些基本配置信息。
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="titan">
  <jta-data-source>java:/OracleDS</jta-data-source>
  <properties>
    <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
  </properties>
</persistence-unit>
</persistence>

开发session bean,定义远程接口和实现业务逻辑
该接口定义了两个方法,一个是创建对象,一个是寻找对象。
package com.titan.travelagent;

import javax.ejb.Remote;

import com.titan.domain.Test_employee;

@Remote
public interface EmployeeRemote {
public void createEmployee(Test_employee em);
public Test_employee findTest_employee(int pKey);
}
实现

package com.titan.travelagent;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.titan.domain.Test_employee;

@Stateless
public class EmployeeBean implements EmployeeRemote{

@PersistenceContext(unitName="titan") private EntityManager manager;

public void createEmployee(Test_employee em){
manager.persist(em);
}
public Test_employee findTest_employee(int pKey){
return manager.find(Test_employee.class, pKey);
}
}
Step4.build.xml解析

eclipse里面右键点击build.xml,选择run as ->ant build…(第三个),注意到它有4个任务,默认的任务是编译和部署,运行一次后,就编译成功。Prepare任务是准备目录。
<?xml version="1.0"?>
<project name="JBoss" default="ejbjar" basedir=".">

<property environment="env"/>
<property name="src.dir" value="${basedir}/src"/>
<property name="src.resources" value="${basedir}/resources"/>
<property name="jboss.home" value="${env.JBOSS_HOME}"/>
<property name="build.dir" value="${basedir}/build"/>
<property name="build.classes.dir" value="${build.dir}/classes"/>

<!-- Build classpath -->
<path id="classpath">
  <fileset dir="${jboss.home}/server/default/lib">
    <include name="*.jar"/>
  </fileset>
  <fileset dir="${jboss.home}/server/default/deploy/ejb3.deployer">
    <include name="*.jar"/>
  </fileset>
  <fileset dir="${jboss.home}/server/default/deploy/jboss-aop-jdk50.deployer">
    <include name="*.jar"/>
  </fileset>
  <fileset dir="${jboss.home}/lib">
    <include name="*.jar"/>
  </fileset>
<pathelement location="${build.classes.dir}"/>
<pathelement location="${basedir}/client-config"/>
</path>

<property name="build.classpath" refid="classpath"/>
<target name="prepare" >
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.classes.dir}"/>
</target>
<target name="compile" depends="prepare">
<javac srcdir="${src.dir}"
    destdir="${build.classes.dir}"
    debug="on"
    deprecation="on"
    optimize="off"
    includes="**">
    <classpath refid="classpath"/>
</javac>
</target>
<target name="ejbjar" depends="compile">
<jar jarfile="build/titan.jar">
  <fileset dir="${build.classes.dir}">
    <include name="com/titan/domain/*.class"/>
    <include name="com/titan/travelagent/*.class"/>
  </fileset>
  <fileset dir="${src.resources}/">
    <include name="META-INF/persistence.xml"/>
  </fileset>
</jar>
<copy file="build/titan.jar" todir="${jboss.home}/server/default/deploy"/>
</target>
<target name="run.client" depends="ejbjar">
<java classname="com.titan.clients.Client" fork="yes" dir=".">
  <classpath refid="classpath"/>
</java>
</target>
</project>
Step5.测试代码

package com.titan.clients;

import com.titan.travelagent.EmployeeRemote;

import com.titan.domain.Test_employee;

import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;

import javax.rmi.PortableRemoteObject;

public class Client
{
public static void main(String [] args)
{
  try
{
    Context jndiContext = getInitialContext();
    //查找JNDI对象
    Object ref = jndiContext.lookup("EmployeeBean/remote");
    EmployeeRemote dao = (EmployeeRemote)ref;
    //创建一个em对象
    Test_employee em = new Test_employee();
    em.setId(1);
    em.setAge(27);
    em.setName("valen won");
    em.setAddress("north 2 building software incubation center south-line chengdu");

    //保存
    dao.createEmployee(em);
    System.out.println("let's find the entity that we just put in the database.");
    Test_employee em2 = dao.findTest_employee(1);
    System.out.println(em2.getName());
    System.out.println(em2.getAddress());
    System.out.println(em2.getAge());

  }
  catch (javax.naming.NamingException ne)
  {
  ne.printStackTrace();
}
}

public static Context getInitialContext()
  throws javax.naming.NamingException
{
  return new javax.naming.InitialContext();
}
}


Step6.测试

启动jboss,进入D:\jboss-4.2.2.GA\bin,运行run.bat默认启动default

antrun.client任务结果如下

Buildfile: D:\BEATRAINING\Eclipse\workspace\ejb41\build.xml
prepare:
compile:
ejbjar:
run.client:
[java] let's find the entity
[java] valen won
[java] north 2 building software incubation center south-line chengdu

[java] 27
BUILD SUCCESSFUL
Total time: 2 seconds
现在数据库中已经有一条记录,如果你再运行一次,就会发现ORA-00001: unique constraint (APS2.SYS_C0019139) violated

不要慌张,改掉client里面的id就可以再运行一次。

OK,第一个EJB例子完成了。

Continue...

完整源代码下载,附件中。ejb3
ejb41.rar


Tags: ejb3   jboss  

类别: JAVA ee |  评论(0) |  浏览(4505) |  收藏
发表评论
看不清楚,换一张