all gone

all gone

EJB 3.0 学习笔记——Entity Bean

在EJB 3.0 学习笔记——准备工作中只是简单的搭好了EJB3.0开发的基本环境,之

后就可以开发最简单的Session Bean了,我感兴趣的还是Entity Bean,所以接下来

我想先试验一下Entity Bean。
 
一、在JBoss中配置好Data Source
我使用的是MySQL数据库,所以首先将MySQL的JDBC驱动复制到
jboss-4.0.3SP1\server\all\lib目录,然后将jboss-4.0.3SP1\docs\examples\jca

下的mysql-ds.xml作出适当修改后复制到jboss-4.0.3SP1\server\all\deploy目录

下,这是我修改后的mysql-ds.xml文件:

<? xml version="1.0" encoding="UTF-8" ?>

<!--  $Id: mysql-ds.xml,v 1.3.2.1 2004/12/01 11:46:00 schrouf Exp $  -->
<!--   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 > MySqlDS </ jndi-name >
    
< connection-url > jdbc:mysql://localhost:3306/test </ connection-url >
    
< driver-class > com.mysql.jdbc.Driver </ driver-class >
    
< user-name > test </ user-name >
    
< password ></ password >
    
< exception-sorter-class-

name > org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter </ excepti

on-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 
    <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 >

这样之后,JBoss下的MySQL Data Source配置完成。

二、创建数据库并编写Entity Bean代码

create table book(
id int not null auto_increment primary key,
title varchar(20) not null,
author varchar(40) not null
);
新建Java Project,导入User Library:EJB3_JBoss,以下是类代码。

// Book.java
package  ejb.bean.entity;

import  java.io.Serializable;

import  javax.persistence.Entity;
import  javax.persistence.GeneratedValue;
import  javax.persistence.GenerationType;
import  javax.persistence.Id;
import  javax.persistence.Table;

@Entity
@Table(name
= " book " )
public   class  Book  implements  Serializable {
 
/**
  * 
  
*/
 
private   static   final   long  serialVersionUID  =   1L ;
 
private  Integer id; 
 
private  String title; 
 
private  String author;
 
 
public  Book() {  
  
super (); 
 } 
 
public  Book(Integer id, String title, String author) { 
  
super ();  
  
this .id  =  id;  
  
this .title  =  title;  
  
this .author  =  author; 
  }
 @Override
 
public  String toString() { 
  
  
return   " Book:  "   +  getId()  +   "  Title  "   +  getTitle()  +   "  

Author 
"  + getAuthor(); 
 }
 
public  String getAuthor() {
  
return  author;
 }
 
 @Id @GeneratedValue(strategy
= GenerationType.AUTO)
 
public  Integer getId() {
  
return  id;
 }
 
public  String getTitle() {
  
return  title;
 }
 
public   void  setAuthor(String author) {
  
this .author  =  author;
 }
 
public   void  setId(Integer id) {
  
this .id  =  id;
 }
 
public   void  setTitle(String title) {
  
this .title  =  title;
 }

}

三、编写一个简单的Stateless Session Bean 并进行测试

// BookTestLocal.java
package  ejb.bean.entity;

import  javax.ejb.Local;

@Local
public   interface  BookTestLocal {

 
public   void  test();
}

// BookTestRemote.java
package  ejb.bean.entity;

import  javax.ejb.Remote;
@Remote
public   interface  BookTestRemote {
 
 
public   void  test();

}

// BookTestBean.java
package  ejb.bean.entity;

import  javax.ejb.Stateless;
import  javax.persistence.EntityManager;
import  javax.persistence.PersistenceContext;

@Stateless
public   class  BookTestBean  implements  BookTestLocal, BookTestRemote {

 @PersistenceContext
 EntityManager em;
 
public   void  test() {
  
//  TODO Auto-generated method stub
  Book book  =   new  Book( null " My first bean book "

" Sebastian " );
  em.persist(book);

 }

}


 

// Client.java
package  ejb.client.entity;

import  ejb.bean.entity. * ;


import  javax.naming.InitialContext;

/**
 * Comment
 *
 * 
@author  <a href="mailto:bill@jboss.org">Bill Burke</a>
 * 
@version  $Revision: 1.1.6.7 $
 
*/
public   class  Client
{
   
public   static   void  main(String[] args)  throws  Exception
   {
      InitialContext ctx 
=   new  InitialContext();
      BookTestRemote book 
=  (BookTestRemote) ctx.lookup

(
" BookTestBean/remote " );

     

   
      book.test();
      
      System.out.println(
" test successful!  " );

   }
}

三、其他文件
将jboss-EJB-3.0_RC5-PFD\docs\tutorial中的找到的jndi.properties、log4j.xml、builder.xml等复制到当前工程中,其中builder.xml需要修改。
//builder.xml

<? xml version="1.0" ?>

<!--  

======================================================================= 

-->
<!--  JBoss build file                                                     

  
-->
<!--  

======================================================================= 

-->

< project  name ="JBoss"  default ="ejbjar"  basedir ="." >

   
< property  file ="../local.properties"   />
   
< property  environment ="env" />
   
< property  name ="src.dir"  value ="${basedir}/src" />
   
< property  name ="jboss.home"  value ="E:/Programming/Servers/jboss-

4.0.3SP1/"
/>
   
< property  name ="jboss.server.config"  value ="all" />
   
< property  name ="build.dir"  value ="${basedir}/build" />
   
< property  name ="build.classes.dir"  value ="${build.dir}/classes" />

   
<!--  Build classpath  -->
   
< path  id ="classpath" >
      
<!--  So that we can get jndi.properties for InitialContext  -->
      
< pathelement  location ="${basedir}" />
      
< fileset  dir ="${jboss.home}/lib" >
         
< include  name ="**/*.jar" />
      
</ fileset >
      
< fileset  dir ="${jboss.home}/server/${jboss.server.config}/lib" >
         
< include  name ="**/*.jar" />
      
</ fileset >
      
< fileset  dir ="${jboss.home}/server/

${jboss.server.config}/deploy/ejb3.deployer"
>
         
< include  name ="*.jar" />
      
</ fileset >
      
< fileset  dir ="${jboss.home}/server/

${jboss.server.config}/deploy/jboss-aop-jdk50.deployer"
>
         
< include  name ="*.jar" />
      
</ fileset >
      
< pathelement  location ="${build.classes.dir}" />
   
</ path >

   
< property  name ="build.classpath"  refid ="classpath" />

   
<!--  

=================================================================== 
-->
   
<!--  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" >
      
< 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/tutorial.jar" >
         
< fileset  dir ="${build.classes.dir}" >
            
< include  name ="**/*.class" />
         
</ fileset >
        
< fileset  dir ="." >
           
< include  name ="META-INF/persistence.xml" />
        
</ fileset >
      
</ jar >
      
< copy  file ="build/tutorial.jar"  todir ="${jboss.home}/server/

${jboss.server.config}/deploy"
/>
   
</ target >

   
< target  name ="run.stateless"  depends ="ejbjar" >
      
< java  classname ="ejb.client.stateless.Client"  fork ="yes"  dir ="." >
         
< classpath  refid ="classpath" />
      
</ java >
   
</ target >
 
 
< target  name ="run.stateful"  depends ="ejbjar" >
       
< java  classname ="ejb.client.stateful.Client"  fork ="yes"  

dir
="." >
          
< classpath  refid ="classpath" />
       
</ java >
 
</ target >
 
 
< target  name ="run.timer"  depends ="ejbjar" >
       
< java  classname ="ejb.client.timer.Client"  fork ="yes"  

dir
="." >
          
< classpath  refid ="classpath" />
       
</ java >
 
</ target >
 
 
< target  name ="run.entity"  depends ="ejbjar" >
        
< java  classname ="ejb.client.entity.Client"  

fork
="yes"  dir ="." >
           
< classpath  refid ="classpath" />
        
</ java >
  
</ target >
 

   
<!--  

=================================================================== 
-->
   
<!--  Cleans up generated stuff                                         

  
-->
   
<!--  

=================================================================== 
-->
   
< target  name ="clean.db" >
      
< delete  dir ="${jboss.home}/server/

${jboss.server.config}/data/hypersonic"
/>
   
</ target >

   
< target  name ="clean" >
      
< delete  dir ="${build.dir}" />
      
< delete  file ="${jboss.home}/server/

${jboss.server.config}/deploy/tutorial.jar"
/>
   
</ target >


</ project >

最后,在工程目录下新建目录META-INF,在目录META-INF新建persistence.xml文件,以下是文件内容:

<? xml version="1.0" encoding="UTF-8" ?>
< persistence >
   
< persistence-unit  name ="test" >
      
< jta-data-source > java:/MySqlDS </ jta-data-source >
      
< properties >
       
< property  name ="hibernate.dialect"  

value
="org.hibernate.dialect.MySQLDialect" />        
        
< property  name ="hibernate.hbm2ddl.auto"  value ="update" />
      
</ properties >
   
</ persistence-unit >
</ persistence >

四、运行测试
run as->ant build后,选择运行目标为run.entity->run。
运行结果:

Buildfile: D:\Programs\Java\EclipseWork\EJB3\build.xml
prepare:
compile:
ejbjar:
run.entity:
     
[ java ]  test successful!
BUILD SUCCESSFUL
Total time: 
9  seconds


MySQL中

select   *   from  book;
id        title                     author
1         My first bean book         Sebastian

已经成功写入。

 

 

 

posted on 2006-05-20 22:38 all gone 阅读(3377) 评论(4)  编辑  收藏 所属分类: Java

评论

# re: EJB 3.0 学习笔记——Entity Bean 2006-05-28 08:06 Richie

<property name="hibernate.hbm2ddl.auto" value="update"/>
变成 value="create" 就不用手动建表了。
EntityBean中比较核心的部分主要还是在映射关系,连锁,lazyfetch上,加油努力。  回复  更多评论   

# re: EJB 3.0 学习笔记——Entity Bean 2006-05-29 21:32 all gone

我这个参考的是JBoss的实现里面的tutorial,Sun的文档也发布了,感觉讲的都很粗,很是期待有一本书可看  回复  更多评论   

# re: EJB 3.0 学习笔记——Entity Bean 2006-06-03 08:30 frend

不行啊,出错了,大家看看我出错在哪里
Buildfile: E:\Documents and Settings\myhome\workspace\EJB3Test\src\build.xml
prepare:
compile:
ejbjar:
run.entity:
[java] Exception in thread "main" javax.naming.NameNotFoundException: BookTestBean not bound
[java] at org.jnp.server.NamingServer.getBinding(NamingServer.java:514)
[java] at org.jnp.server.NamingServer.getBinding(NamingServer.java:522)
[java] at org.jnp.server.NamingServer.getObject(NamingServer.java:528)
[java] at org.jnp.server.NamingServer.lookup(NamingServer.java:252)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[java] at java.lang.reflect.Method.invoke(Method.java:585)
[java] at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:294)
[java] at sun.rmi.transport.Transport$1.run(Transport.java:153)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at sun.rmi.transport.Transport.serviceCall(Transport.java:149)
[java] at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
[java] at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
[java] at java.lang.Thread.run(Thread.java:595)
[java] at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
[java] at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
[java] at sun.rmi.server.UnicastRef.invoke(Unknown Source)
[java] at org.jnp.server.NamingServer_Stub.lookup(Unknown Source)
[java] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:610)
[java] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:572)
[java] at javax.naming.InitialContext.lookup(Unknown Source)
[java] at ejb.bean.entity.Client.main(Client.java:17)
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 10 seconds
  回复  更多评论   

# re: EJB 3.0 学习笔记——Entity Bean 2006-06-16 19:47 all gone

@frend
你的BookTestBean 没有部署成功  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: