gembin

OSGi, Eclipse Equinox, ECF, Virgo, Gemini, Apache Felix, Karaf, Aires, Camel, Eclipse RCP

HBase, Hadoop, ZooKeeper, Cassandra

Flex4, AS3, Swiz framework, GraniteDS, BlazeDS etc.

There is nothing that software can't fix. Unfortunately, there is also nothing that software can't completely fuck up. That gap is called talent.

About Me

 

EJB3 学习Notes 1。

[Notes 1]   Get Started --- setup environment and Helloworld Example
   
       1.  建立开发环境,安装JDK5.0 Up,设置JAVA_HOME
              下载EJB3 Container,本文采用Sun的GlassFish V2,glassfish-installer-v2ur1-b09d-windows.jar,
              java -Xmx256m -jar glassfish-installer-v2ur1-b09d-windows.jar
              cd glassfish
              lib\ant\bin\ant -f setup.xml
        
       2.  启动GlassFish,把glassfish_home\bin 加到Path, 执行Command,asadmin start-domain domain1 或者
asadmin start-domain 将会启动默认
            的domain
. 用asadmin stop-domain domain1来shutdown GlassFish.
           关于admin command 可以参考
http://docs.sun.com/app/docs/doc/819-3675/6n5slue6r?a=expand
       3.  建立测试环境,添加以下的Jars到ClassPath,
            GlassFish\lib\admin-cli.jar
            GlassFish\lib\appserv-rt.jar
            GlassFish\lib\appserv-ext.jar
            GlassFish\lib\javaee.jar

            创建jndi.properties,放在src目录下,     

                     java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory
          java.naming.factory.url.pkgs
=com.sun.enterprise.naming
          java.naming.factory.state
=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl
          org.omg.CORBA.ORBInitialHost
=localhost
          org.omg.CORBA.ORBInitialPort
=3700

          创建sun-ejb-jar.xml,放在META-INF目录下,

       <?xml version="1.0" encoding="UTF-8"?>
       <!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN" "http://www.sun.com
       /software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
       <sun-ejb-jar>
        <enterprise-beans>
        </enterprise-beans>
       </sun-ejb-jar>
       创建数据库表:
       
 CREATE TABLE "PEOPLE" 

   (  "ID" 
NUMBER(9,0NOT NULL ENABLE, 

         "NATION" 
VARCHAR2(20 BYTE) NOT NULL ENABLE, 

         "CITY" 
VARCHAR2(50 BYTE), 

         "PHONE_NUMBER" 
VARCHAR2(50 BYTE), 

         "ZIP_CODE" 
VARCHAR2(20 BYTE), 

         "NAME" 
VARCHAR2(200 BYTE) NOT NULL ENABLE, 

          
CONSTRAINT "PEOPLE_PK" PRIMARY KEY ("ID")

  USING 
INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 

  STORAGE(INITIAL 
65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645

  PCTINCREASE 
0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)

  TABLESPACE "DEMO"  ENABLE

   ) PCTFREE 
10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING

  STORAGE(INITIAL 
65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645

  PCTINCREASE 
0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)

  TABLESPACE "DEMO" ;
       配置数据库DataSource 以及JNDI
    4.  开始EJB3的第1个helloworld,
          
(1).创建1个Entity
package ejb3.example.entity;
import
 java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name
="PEOPLE")
@NamedQuery(name 
= "People.findAll", query = "SELECT p FROM People p")
@SequenceGenerator(name 
= "PeopleSequence",sequenceName="SEQ_PEOPLE",initialValue=1,allocationSize=1)
public class People implements Serializable{
    @Id
    @Column(name
="ID",nullable=false)
    @GeneratedValue(strategy 
= GenerationType.SEQUENCE,generator="PeopleSequence")
    
private int id;
    
    @Column(name
="NATION",nullable=false)
    
private String nation;
    
    @Basic
    
private String city;
    
    @Column(name
="PHONE_NUMBER")
    
private String phoneNumber;
    
    @Column(name
="ZIP_CODE")
    
private String zipCode;
    
    @Column(name
="NAME",nullable=false)
    
private String name;
    
    
    
public int getId() {
        
return id;
    }
    
public void setId(int id) {
        
this.id = id;
    }
    
public String getNation() {
        
return nation;
    }
    
public void setNation(String nation) {
        
this.nation = nation;
    }
    
public String getCity() {
        
return city;
    }
    
public void setCity(String city) {
        
this.city = city;
    }
    
public String getPhoneNumber() {
        
return phoneNumber;
    }
    
public void setPhoneNumber(String phoneNumber) {
        
this.phoneNumber = phoneNumber;
    }
    
public String getZipCode() {
        
return zipCode;
    }
    
public void setZipCode(String zipCode) {
        
this.zipCode = zipCode;
    }
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    
    
    
public String toString(){
        
return new StringBuilder()
        .append(
"id="+id+"\n")
        .append(
"name="+name+"\n")
        .append(
"nation="+nation+"\n")
        .append(
"city="+city+"\n")
        .append(
"zipCode="+zipCode+"\n")
        .append(
"phoneNumber="+phoneNumber).toString();
    }
}
         创建persistence.xml放在META-INF目录下,定义Persistence Unit提供给EntityManager使用
<?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">
    
<persistence-unit name="PeoplePersistenceUnit" transaction-type="JTA">
        
<provider>
            oracle.toplink.essentials.PersistenceProvider
        
</provider>
        
<jta-data-source>oracleDataSourceJNDI</jta-data-source>
        
<!--mapping-file>ejb3/example/entity/orm.xml</mapping-file-->
        
<class>ejb3.example.entity.People</class>
        
<properties>
            
<property name="toplink.target-server" value="SunAS9"/>
            
<property name="toplink.target-database" value="Oracle"/>
            
<property name="toplink.logging.level" value="FINE"/>
            
<!--<property name="toplink.ddl-generation" value="drop-and-create-tables"/>
            
-->
        
</properties>
    
</persistence-unit>

</persistence>
         
        
(2) 创建IPeoplePersistenceService来做Persistence Facade,使用EntityManager的API
         

package ejb3.example.service.api;

import java.util.List;

import javax.ejb.Local;

import ejb3.example.entity.People;


public interface IPeoplePersistenceService {
       
    
public void save(People p);
    
    
public People find(int id);
    
    
public List<People>findAll();
    
    
public void update(People p);
    
    
public void delete(int id);
    
    
public List<People>query(String query);
    
    
public List<People> queryByPagination(String query,int startPage,int pageSize);
}
 
         (3). 实现Persistent Service
        


package ejb3.example.service.impl;

import java.util.List;

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

import ejb3.example.entity.People;

@Stateless
public class PeoplePersistenceServiceBean implements IPeoplePersistenceService {
    @PersistenceContext(unitName
="PeoplePersistenceUnit")
    
private EntityManager entityManager;
    
    
private static final int DEFAULT_PAGE_SIZE=20;
    
public List<People>query(String query){
        
return entityManager.createQuery(query).getResultList();
    }
    
    
public List<People>findAll(){
        
return entityManager.createNamedQuery("People.findAll").getResultList();
    }
    
    
public void save(People p) {
        assertNotNull(p);
        entityManager.persist(p);
    }
    
    
public People find(int id){
        
return entityManager.find(People.class, id);
    }

    
public void delete(int id) {
        People p
=entityManager.find(People.class, id);
        
if(p!=null)
         entityManager.remove(p);
    }

    
public void update(People p) {
        assertNotNull(p);
        entityManager.merge(p);
    }
    
    
    
public List<People> queryByPagination(String query,int startPage,int pageSize){
        Query q
=entityManager.createQuery(query);
        q.setMaxResults(pageSize
<1?DEFAULT_PAGE_SIZE:pageSize);
        
if(startPage<1)startPage=1;
        q.setFirstResult(startPage
*pageSize);
        
return q.getResultList();
    }
    
    
    
private void assertNotNull(Object o){
         
if(null==o)
             
throw new RuntimeException("Object cannot be null");
    }
     
}

        (4). 创建Business Logic的Service Interface

package ejb3.example.service.api;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;

import ejb3.example.entity.People;



public interface IPeopleManager {
      
      
public People findById(int id);
      
      
public List<People> findByName(String name);
      
      
public List<People> findByNation(String nation);
      
      
public List<People> findAll();
      
      
public void update(People p);
      
      
public void deleteById(int id);
      
      
public void save(People p);
      
      
public List<People> queryByPagination(String query,int startPage,int pageSize);
    
}
      
      (5).创建Stateless Bean来处理Busniess Logic , 它实现IPeopleManager


package ejb3.example.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import ejb3.example.entity.People;


@
Local(IPeopleManager.class)
@Stateless(name
="peopleManagerBean", mappedName="peopleManagerBeanJNDI"
public class PeopleManagerBean implements IPeopleManager {

    
private static final String PEOPLE_ENTITY=People.class.getSimpleName();

    @EJB IPeoplePersistenceService persister;

    
    
public void deleteById(int id) {
        persister.delete(id);

    }

    
public List<People> findAll() {
        
return persister.findAll();
    }

    
public People findById(int id) {
        
return persister.find(id);
    }

    
public List<People> findByName(String name) {
        
return  persister.query("select p from "+PEOPLE_ENTITY+" p where p.name=:"+name);
    }

    
public List<People> findByNation(String nation) {
        
return  persister.query("select p from "+PEOPLE_ENTITY+" p where p.nation=:"+nation);
    }

    
public List<People> queryByPagination(String query,int startPage, int pageSize) {
        
return  persister.queryByPagination(query, startPage, pageSize);

    }

    
public void save(People p) {
        persister.save(p);
    }

    
public void update(People p) {
        persister.update(p);
    }
     
}

       (6). Export Jar,把它放在glassfish\domains\domain1\autodeploy,这个会再GlassFish启动的时候自动部署或者打开http://localhost:4848,用默认的帐号登陆来Deploy
             (user: admin   password: adminadmin)
            

        (7). 创建测试客户端
 

package ejb3.example.client;

import java.sql.SQLException;
import java.util.Iterator;

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

import ejb3.example.service.api.IPeopleManager;
import ejb3.example.entity.People;


public class TestClient {

    
/**
     * Method documentation to be filled
     * TODO
     *
     * 
@param args
     * 
@throws NamingException 
     * 
@throws SQLException 
     * 
@throws ClassNotFoundException 
     * 
@throws IllegalAccessException 
     * 
@throws InstantiationException 
     
*/
    
public static void main(String[] args) throws NamingException, SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

        Context context 
= new InitialContext ();
        IPeopleManager mgr 
= (IPeopleManager)context.lookup ("peopleManagerBeanJNDI");
        People p
=mgr.findById(1);
        p.setCity(
"beijing Chaoyang");
        p.setName(
"gembin");
        p.setNation(
"Great China");
        p.setPhoneNumber(
"xxxx");
        p.setZipCode(
"100000");
        mgr.update(p);
        Iterator
<People>ps=mgr.findAll().iterator();
        
while(ps.hasNext()){
            System.out.println(
"*********************");
            System.out.println(ps.next());
            System.out.println(
"*********************");
        }
     
    }
}


       

posted on 2009-02-25 11:21 gembin 阅读(1787) 评论(2)  编辑  收藏 所属分类: EJB3

评论

# re: EJB3 学习Notes 1。 2009-02-25 12:40 3条鱼

晕倒,就这么点  回复  更多评论   

# re: EJB3 学习Notes 1。 2009-02-25 14:43 gembin

hehe 刚才还没写完。。。  回复  更多评论   


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


网站导航:
 

导航

统计

常用链接

留言簿(6)

随笔分类(440)

随笔档案(378)

文章档案(6)

新闻档案(1)

相册

收藏夹(9)

Adobe

Android

AS3

Blog-Links

Build

Design Pattern

Eclipse

Favorite Links

Flickr

Game Dev

HBase

Identity Management

IT resources

JEE

Language

OpenID

OSGi

SOA

Version Control

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

free counters