BeanSoft's Java Blog
免费电子书/视频《MyEclipse 6 Java 开发中文教程》作者刘长炯官方博客 经济危机 珍惜生命 远离培训
2007.09.04
By BeanSoft@126.com


下载此视频: http://download.gro.clinux.org/beansoft/jboss_myeclipse_entity.swf 4.12 MB 08分31秒

下载源代码: http://download.gro.clinux.org/beansoft/MyEntityBean.zip 437KB

这是使用 MyEclipse 开发的一个运行成功的 JBoss 的 Entity Bean. 源代码可以导入 MyEclipse, 然后编译发布.
环境:
JDK 1.5
JBoss 4.2.1 GA
MyEclipse 5.5.1 GA
Derby

下载项目源码 MyEntityBean.zip
文件列表如下所示:
2007-09-05  15:33               429 .classpath
2007-09-05  15:29    <DIR>          .myeclipse
2007-09-05  15:29               175 .mymetadata
2007-09-05  15:33             1,137 .project
2007-09-05  15:30    <DIR>          .settings
2007-09-05  15:33    <DIR>          classes
2007-09-05  16:13               390 client.txt
2007-09-05  16:12               102 create.sql
2007-09-05  16:14               891 derby-ds.xml
2007-09-05  16:12           465,668 derbyclient.jar
2007-09-05  15:33    <DIR>          src

操作步骤:

首先当然是配置数据源了.
1. 先请把 derbyclient.jar 复制到 $JBOSS_HOME/server/default/lib/ 下, 然后重启 JBoss 服务器.

2. 在 MyEclipse 中启动 MyEclipse Derby 数据库服务器, 并创建一个测试表并插入一条数据:

createtable myuser (id intprimarykey, username varchar(20));
insert into myuser values(1, 'test'); 

3. 编写一个 DataSource 配置文件: derby-ds.xml (项目文件中已经附带), 并复制到目录 $JBOSS_HOME/server/default/deploy/ 下, 注意这些变量:
 <jndi-name>DerbyDS</jndi-name> 和       <connection-url>jdbc:derby://localhost:1527/myeclipse;create=true</connection-url>

      <!-- The driver class -->
      <driver-class>org.apache.derby.jdbc.ClientDriver</driver-class>

      <!-- The login and password -->
      <user-name>app</user-name>
      <password>app</password> 这几个一定要和你上一步建表时候所用的数据库连接的 URL, 用户名, 密码一致.
      jndi-name 则是最后 EJB 所能访问到的数据源的地址.
      文件完整内容示例:

<?xmlversion="1.0"encoding="UTF-8"?><!-- The Hypersonic embedded database JCA connection factory config --><!-- $Id: hsqldb-ds.xml 63175 2007-05-21 16:26:06Z rrajesh $ --><datasources><local-tx-datasource><!-- The jndi name of the DataSource, it is prefixed with java:/ --><!-- Datasources are not available outside the virtual machine --><jndi-name>DerbyDS</jndi-name><connection-url>jdbc:derby://localhost:1527/myeclipse;create=true</connection-url><!-- The driver class --><driver-class>org.apache.derby.jdbc.ClientDriver</driver-class><!-- The login and password --><user-name>app</user-name><password>app</password><!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml --><metadata><type-mapping>Derby</type-mapping></metadata></local-tx-datasource></datasources>

至此, 数据源算是配置完毕. 你可以在 JBoss 的 JNDI View 中查看到这个 DerbyDS.

4. 导入项目 MyEntityBean 到 MyEclipse.

5. 将文件 $JBOSS_HOME/client/jbossall-client.jar 加入到项目的 Build Path(相当于 CLASSPATH) 中, 然后通过 MyEclipse 进行编译和部署. 部署后同样可以通过 JNDIView 来检查是否发布成功了 EJB.

6. 运行 TestMyEntityBean 来进行调用测试, 成功后可以在后台数据库看到插入的数据.

附 Bean 源码:

测试类:

import java.util.*;
import javax.naming.*; 

publicclass TestMyEntityBean { 

    /**     * @param args     */publicstaticvoid main(String[] args) throws Exception {
        // 手工初始化的过程
        Hashtable properties = new Hashtable();
        // 配置驱动程序, JBoss 特定的
        properties.put(Context.INITIAL_CONTEXT_FACTORY,
                "org.jnp.interfaces.NamingContextFactory");
        // 配置 URL, JBoss 特定的
        properties.put(Context.PROVIDER_URL, "jnp://localhost");
        InitialContext ctx = new javax.naming.InitialContext(properties);
        // 初始化, 相当于打开文件浏览器    
        entity.TestuserFacadeRemote remote = (entity.TestuserFacadeRemote)ctx.lookup("TestuserFacade/remote");
        entity.Testuser user = new entity.Testuser();
        user.setId(3);
        user.setUsername("username3");
        remote.save(user);
        ctx.close();
    } 

} 

Bean Remote 接口:

package entity; 

import java.util.List;
import javax.ejb.Remote; 

/** * Remote interface for TestuserFacade. *  * @author MyEclipse Persistence Tools */
@Remote
publicinterface TestuserFacadeRemote {
    publicvoid save(Testuser transientInstance); 

    publicvoid delete(Testuser persistentInstance); 

    public Testuser update(Testuser detachedInstance); 

    public Testuser findById(Integer id); 

    public List findByProperty(String propertyName, Object value);
} 

Bean 类:

package entity; 

import java.util.List;
import java.util.logging.Level;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; 

/** * Facade for entity Testuser. *  * @see entity.Testuser * @author MyEclipse Persistence Tools */
@Stateless
publicclass TestuserFacade implements TestuserFacadeRemote { 

    @PersistenceContext
    private EntityManager entityManager; 

    publicvoid save(Testuser transientInstance) {
//        EntityManagerHelper.log("saving Testuser instance", Level.INFO, null);try {
            entityManager.persist(transientInstance);
//            EntityManagerHelper.log("save successful", Level.INFO, null);
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("save failed", Level.SEVERE, re);throw re;
        }
    } 

    publicvoid delete(Testuser persistentInstance) {
//        EntityManagerHelper.log("deleting Testuser instance", Level.INFO, null);try {
            entityManager.remove(persistentInstance);
//            EntityManagerHelper.log("delete successful", Level.INFO, null);
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("delete failed", Level.SEVERE, re);throw re;
        }
    } 

    public Testuser update(Testuser detachedInstance) {
//        EntityManagerHelper.log("updating Testuser instance", Level.INFO, null);try {
            Testuser result = entityManager.merge(detachedInstance);
//            EntityManagerHelper.log("update successful", Level.INFO, null);return result;
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("update failed", Level.SEVERE, re);throw re;
        }
    } 

    public Testuser findById(Integer id) {
//        EntityManagerHelper.log("finding Testuser instance with id: " + id,//                Level.INFO, null);try {
            Testuser instance = entityManager.find(Testuser.class, id);
            return instance;
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("find failed", Level.SEVERE, re);throw re;
        }
    } 

    @SuppressWarnings("unchecked")
    public List<Testuser> findByProperty(String propertyName, Object value) {
//        EntityManagerHelper.log("finding Testuser instance with property: "//                + propertyName + ", value: " + value, Level.INFO, null);try {
            String queryString = "select model from Testuser model where model."
                    + propertyName + "= :propertyValue";
            return entityManager.createQuery(queryString).setParameter(
                    "propertyValue", value).getResultList();
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("find by property name failed",//                    Level.SEVERE, re);throw re;
        }
    } 

    @SuppressWarnings("unchecked")
    public List<Testuser> findAll() {
//        EntityManagerHelper.log("finding all Testuser instances", Level.INFO,//                null);try {
            String queryString = "select model from Testuser model";
            return entityManager.createQuery(queryString).getResultList();
        } catch (RuntimeException re) {
//            EntityManagerHelper.log("find all failed", Level.SEVERE, re);throw re;
        }
    }
} 

Entity 类:

package entity; 

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; 

/** * Testuser generated by MyEclipse Persistence Tools */
@Entity
@Table(name = "TESTUSER", schema = "APP", uniqueConstraints = {})
publicclass Testuser implements java.io.Serializable { 

    // Fields private Integer id; 

    private String username; 

    // Constructors /** default constructor */public Testuser() {
    } 

    /** minimal constructor */public Testuser(Integer id) {
        this.id = id;
    } 

    /** full constructor */public Testuser(Integer id, String username) {
        this.id = id;
        this.username = username;
    } 

    // Property accessors
    @Id
    @Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = true)
    public Integer getId() {
        returnthis.id;
    } 

    publicvoid setId(Integer id) {
        this.id = id;
    } 

    @Column(name = "USERNAME", unique = false, nullable = true, insertable = true, updatable = true, length = 20)
    public String getUsername() {
        returnthis.username;
    } 

    publicvoid setUsername(String username) {
        this.username = username;
    } 

}



posted on 2007-09-05 21:21 BeanSoft 阅读(3202) 评论(9)  编辑  收藏 所属分类: Java EEMyEclipse