最近项目录要用到EJB3.0, 对于象我一样没有接确过ejb的人来说, 开发首个应用还是比较复杂的, 下面是一个EJB3.0 Entity Bean开发实例,
**** EntityBean 开发****
1. 配置应用相关的数据源(针对不同的数据库进行不同的配置)
这里按照MySQL5进行配置.
1.1 找到MySQL的JDBC驱动jar(我这里是:mysql.jar),将该jar
文件复制到[jboss-install-root]\server\default\lib下
1.2 编写MySQL的数据源配置文件 "mysql-ds.xml"
内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>COOTMEMySQLDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK</connection-url>
<driver-class>org.gjt.mm.mysql.Driver</driver-class>
<user-name>root</user-name>
<password>admin</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
重新启动JBOSS服务器,检查http://localhost:8080/jmx-console路径下的
jboss.jca出现如下的配置信息为成功配置该数据源:
name=COOTMEMySQLDS,service=DataSourceBinding
name=COOTMEMySQLDS,service=LocalTxCM
name=COOTMEMySQLDS,service=ManagedConnectionFactory
name=COOTMEMySQLDS,service=ManagedConnectionPool
如果未出现,则检查相关的配置是否正确?
1.3 实现persistence.xml文件
<persistence>
<!-- Database name -->
<persistence-unit name="test">
<!-- Configurated in jboss DS -->
<jta-data-source>java:/COOTMEMySQLDS</jta-data-source>
<properties>
<!-- "update" dont delete tables and update table's data -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
注意:该文件请放置[工程目录]\src\META-INF\persistence.xml下
1.4 实现EntityBean
此处为:Student.java
package com.cootme.ejb3.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
@SuppressWarnings("serial")
@Entity
@Table(name = "Student")
public class Student implements Serializable{
private Integer id;
private String name;
private Integer age;
private String sex;
private String mobile;
private String email;
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(nullable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(nullable=true)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Column(nullable=true)
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Column(nullable=true)
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Column(nullable=true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
1.5 实现SessionBean的业务操作类
1.5.1 业务类接口:StudentDAO.java
package com.cootme.ejb3.seesion.student;
import java.util.List;
public interface StudentDAO {
public List getStudentList();
public List getStudentByName(String _name);
}
1.5.2 业务类实现:StudentDAOBean.java
package com.cootme.ejb3.seesion.student.bean;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.cootme.ejb3.seesion.student.StudentDAO;
@Stateless
@Remote(StudentDAO.class)
public class StudentDAOBean implements StudentDAO {
//===================================================
//injection EntityManager object
//unitName="test" here "test" from persistence.xml unit name
@PersistenceContext(unitName="test")
protected EntityManager em;
public List getStudentByName(String _name) {
List studentList = null;
//===============================================
//invoke the named query
Query query = em.createQuery("from Student as s where s.name=?1 order by s.id asc");
query.setParameter(1, _name);
//===============================================
//execute query
studentList = query.getResultList();
return studentList;
}
public List getStudentList() {
List studentList = null;
//===============================================
//invoke the named query
Query query = em.createQuery("from Student as s order by s.id asc");
//===============================================
//execute query
studentList = query.getResultList();
return studentList;
}
}
1.6 实现测试业务类客户端代码:StudentClient.java
package com.cootme.blogic;
import java.util.List;
import java.util.Iterator;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.cootme.ejb3.entity.Student;
import com.cootme.ejb3.seesion.student.StudentDAO;
public class StudentClient {
//======================================================
Properties props = null;
InitialContext ctx = null;
private void init(){
if(props == null){
props = new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
}
try{
if(ctx == null){
ctx = new InitialContext(props);
}
}catch(NamingException ne){
System.out.println("==>COOTME-1: Naming exception");
ne.printStackTrace();
}
}
public void getStudentByName(String _name){
List studentList = null;
try{
init();
StudentDAO dao = (StudentDAO)ctx.lookup("StudentDAOBean/remote");
studentList = dao.getStudentByName(_name);
if(studentList != null){
Iterator i = studentList.iterator();
while(i.hasNext()){
Student s = (Student)i.next();
System.out.println("=========== Student table datas ===========");
System.out.println(s.getId() + " " + s.getName() + " " + s.getSex() + " " +
s.getAge() + " " + s.getMobile() + " " + s.getEmail());
System.out.println("===========================================");
}
}
}catch(NamingException ne){
System.out.println("==>COOTME-2: Naming exception");
ne.printStackTrace();
}
}
public void getStudents(){
List studentList = null;
try{
init();
StudentDAO dao = (StudentDAO)ctx.lookup("StudentDAOBean/remote");
studentList = dao.getStudentList();
if(studentList != null){
Iterator i = studentList.iterator();
while(i.hasNext()){
Student s = (Student)i.next();
System.out.println("=========== Student table datas ===========");
System.out.println(s.getId() + " " + s.getName() + " " + s.getSex() + " " +
s.getAge() + " " + s.getMobile() + " " + s.getEmail());
System.out.println("===========================================");
}
}
}catch(NamingException ne){
System.out.println("==>COOTME-2: Naming exception");
ne.printStackTrace();
}
}
}
1.7 测试应用的web页面代码:index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="com.cootme.blogic.StudentClient"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello, COOTME</title>
</head>
<body>
<h1>Hello</h1>
<%
StudentClient sc = new StudentClient();
sc.getStudentByName("geyou");
sc.getStudents();
%>
</body>
</html>
1.8 编译、发布到jboss服务器中:build.xml
<?xml version="1.0"?>
<!-- ======================================================================= -->
<!-- EJB3 WebProject build file -->
<!-- ======================================================================= -->
<project name="WebProject" default="ejbjar" basedir="..">
<property environment="env" />
<property name="app.dir" value="${basedir}/WebProject" />
<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="${basedir}/ejbjars">
<include name="*.jar" />
</fileset>
<pathelement location="${build.classes.dir}" />
</path>
<!-- =================================================================== -->
<!-- Prepares the build directory -->
<!-- =================================================================== -->
<target name="prepare">
<mkdir dir="${build.dir}" />
<mkdir dir="${build.classes.dir}" />
</target>
<!-- =================================================================== -->
<!-- Compiles the source code -->
<!-- =================================================================== -->
<target name="compile" depends="prepare" description="编绎">
<javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" optimize="off" includes="**">
<classpath refid="build.classpath" />
</javac>
</target>
<target name="ejbjar" depends="compile,createwar" description="创建EJB发布包">
<jar jarfile="${app.dir}/cootmeejb3.jar">
<fileset dir="${build.classes.dir}">
<include name="**/*.class" />
</fileset>
<metainf dir="${src.dir}/META-INF">
<include name="**" />
</metainf>
</jar>
</target>
<target name="createwar" description="创建WAR包">
<jar jarfile="${app.dir}/WebProject.war">
<fileset dir="${app.dir}/WebContent"/>
</jar>
</target>
<target name="deploy" depends="ejbjar" description="发布到JBOSS">
<copy file="${app.dir}/cootmeejb3.jar" todir="${jboss.home}/server/${jboss.server.config}/deploy" />
<copy file="${app.dir}/WebProject.war" 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/WebProject.jar" />
</target>
</project>
1.9 在dos或者eclipse开发环境下运行build.xml,即可自动部署到服务器中
部署成功,在jboss的dos窗口中可以到如下的信息:
14:06:22,343 INFO [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=cootm
eejb3.jar,name=StudentDAOBean,service=EJB3 with dependencies:
14:06:22,343 INFO [JmxKernelAbstraction] persistence.units:jar=cootmeejb3
.jar,unitName=test
14:06:22,363 INFO [EJBContainer] STARTED EJB: com.cootme.ejb3.seesion.student.b
ean.StudentDAOBean ejbName: StudentDAOBean
14:06:22,373 INFO [EJB3Deployer] Deployed: file:/D:/MySoft/jboss-4.2.0.GA/serve
r/default/deploy/cootmeejb3.jar
14:06:22,453 INFO [TomcatDeployer] deploy, ctxPath=/cootmeweb, warUrl=.../tmp/d
eploy/tmp57731WebProject-exp.war/
1.10 打开IE浏览器输入以下地址:http://localhost:8080/cootmeweb/
即可看到jboss后台的dos窗口的输出:
13:55:11,368 INFO [STDOUT] =========== Student table datas ===========
13:55:11,368 INFO [STDOUT] 1 geyou NA 28 13426445816
[email protected]
13:55:11,368 INFO [STDOUT] ===========================================
13:55:11,388 INFO [STDOUT] =========== Student table datas ===========
13:55:11,388 INFO [STDOUT] 1 geyou NA 28 13426445816
[email protected]
13:55:11,388 INFO [STDOUT] ===========================================
13:55:11,388 INFO [STDOUT] =========== Student table datas ===========
13:55:11,388 INFO [STDOUT] 2 cootme NA 28 13426445816
[email protected]
13:55:11,388 INFO [STDOUT] ===========================================
13:55:11,388 INFO [STDOUT] =========== Student table datas ===========
13:55:11,388 INFO [STDOUT] 3 HFH NA 28 13426445816
[email protected]
13:55:11,388 INFO [STDOUT] ===========================================
到此全部的ejb3的entity bean和session bean的开发全部结束,可以好好轻松一下了,呵呵...
注意:在以上的开发之前,需要准备好MySQL数据库,本人用的是MySQL5,使用的是test数据库实例,
其中有一张表名为:student,结构如下:
DROP TABLE `test`.`student`;
CREATE TABLE `test`.`student` (
`id` INT,
`name` VARCHAR(20),
`age` INT,
`sex` CHAR(2),
`mobile` VARCHAR(15),
`email` VARCHAR(50)
) ENGINE=InnoDB;
请大家对应自己的表结构。
本文引用自http://blog.csdn.net/ThirdDimension/archive/2008/06/26/2589741.aspx, 感谢 第三空间的朋友