ejb3.0学习

注意::在客户端写测试代码的时候要导入jbossall-client.jar 否则报错

Cannot instantiate class: org.jnp.interfaces.NamingContextFactory
Exception in thread "main" java.lang.NullPointerException
 at com.foshanshop.ejb3.app.QueueSender.main(QueueSender.java:)

1、 安装JBOSS 配置环境变量JBOSS_HOME  JAVA_HOME

2、安装MYECLIPSE 5.5

3、安装mysql

      建立数据库

    create table `test`.`usertable`(
        `userid` int not null,
       `username` varchar(20) not null,
       `userpassword` varchar(20) not null,
        primary key (`userid`)
    );

    create index `PRIMARY` on `test`.`usertable`(`userid`);

4、将数据库驱动考到jboss-4.2.1.GA/server/all/lib 

jboss-4.2.1.GA/docs/examples/jca  下的mysql-ds.xml考贝到jboss-4.2.1.GA/server/all/deploy 或jboss-4.2.1.GA/server/default/deploy进行修改!

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

<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>root</user-name>
    <password>pyrgz</password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-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 - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
      -->

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml -->
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

实例1、创建HELLOWROD 的LOCAL与REMOTE

package session;
import javax.ejb.Remote;


@Remote
public interface HelloBeanRemote {
 public String sayHello(String name);
}


package session;
import javax.ejb.Local;


@Local
public interface HelloBeanLocal {

}

package session;
import javax.ejb.Stateless;
@Stateless
public class HelloBean implements HelloBeanLocal, HelloBeanRemote {
 public String sayHello(String name) {
  // TODO Auto-generated method stub
  return "hello"+name;
 }
}

java测试

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

import session.HelloBeanRemote;

public class HelloTest {

 public static void main(String[] args) throws NamingException {
  // TODO Auto-generated method stub
  Hashtable properties=new Hashtable();
  properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
  properties.put(Context.PROVIDER_URL, "jnp://localhost");
  InitialContext ctx;
  /*Properties props = new Properties();
  props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
  props.setProperty("java.naming.provider.url", "localhost:8080");
  props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming"); */
  ctx = new InitialContext(properties);
  HelloBeanRemote helloworld = (HelloBeanRemote) ctx.lookup("HelloBean/remote");
  System.out.println(helloworld.sayHello("aaaa"));
  ctx.close(); 
 }

}

JSP测试

  <% 
      Properties prop=new Properties();
      prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jndi.properties"));
      InitialContext ctx;
      ctx = new InitialContext(prop);
      session.HelloBeanRemote helloworld = (session.HelloBeanRemote) ctx.lookup("HelloBean/remote");
      out.println(helloworld.sayHello("aaaa"));
      ctx.close();
     
    %>

JSP测试数据库连接问题!

<%
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:/MySqlDS");//这里要和mysql-ds.xml中对应
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM usertable");
while ( rs.next() ){
 out.println(rs.getString("username") + "<br>");
}
conn.close();

%>

实例2、EJB实体

实体BEAN接口

package entity;

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

/**
 * Remote interface for UsertableFacade.
 *
 * @author MyEclipse Persistence Tools
 */
@Remote
public interface UsertableFacadeRemote {
 public void save(Usertable transientInstance);

 public void delete(Usertable persistentInstance);

 public Usertable update(Usertable detachedInstance);

 public Usertable 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 Usertable.
 *
 * @see entity.Usertable
 * @author MyEclipse Persistence Tools
 */
@Stateless
public class UsertableFacade implements UsertableFacadeRemote {

 @PersistenceContext(unitName="mysql")
 private EntityManager entityManager;

 public void save(Usertable transientInstance) {
 
  try {
   entityManager.persist(transientInstance);
  
  } catch (RuntimeException re) {
 
   throw re;
  }
 }

 public void delete(Usertable persistentInstance) {
 
  try {
   entityManager.remove(persistentInstance);
  
  } catch (RuntimeException re) {

   throw re;
  }
 }

 public Usertable update(Usertable detachedInstance) {
 
  try {
   Usertable result = entityManager.merge(detachedInstance);
  
   return result;
  } catch (RuntimeException re) {
 
   throw re;
  }
 }

 public Usertable findById(Integer id) {
  
  
  try {
   Usertable instance = entityManager.find(Usertable.class, id);
   return instance;
  } catch (RuntimeException re) {

   throw re;
  }
 }

 @SuppressWarnings("unchecked")
 public List<Usertable> findByProperty(String propertyName, Object value) {
 
  
  try {
   String queryString = "select model from Usertable model where model."
     + propertyName + "= :propertyValue";
   return entityManager.createQuery(queryString).setParameter(
     "propertyValue", value).getResultList();
  } catch (RuntimeException re) {
 
   throw re;
  }
 }

 @SuppressWarnings("unchecked")
 public List<Usertable> findAll() {
  
  try {
   String queryString = "select model from Usertable model";
   return entityManager.createQuery(queryString).getResultList();
  } catch (RuntimeException re) {
  
   throw re;
  }
 }
}

实体BEAN

package entity;

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

/**
 * Usertable generated by MyEclipse Persistence Tools
 */
@Entity
@Table(name = "usertable", catalog = "test")
public class Usertable implements java.io.Serializable {

 // Fields

 private Integer userid;

 private String username;

 private String userpassword;

 // Constructors

 /** default constructor */
 public Usertable() {
 }

 /** full constructor */
 public Usertable(Integer userid, String username, String userpassword) {
  this.userid = userid;
  this.username = username;
  this.userpassword = userpassword;
 }

 // Property accessors
 @Id
 @Column(name = "userid", unique = false, nullable = false, insertable = true, updatable = true)
 public Integer getUserid() {
  return this.userid;
 }

 public void setUserid(Integer userid) {
  this.userid = userid;
 }

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

 public void setUsername(String username) {
  this.username = username;
 }

 @Column(name = "userpassword", unique = false, nullable = false, insertable = true, updatable = true, length = 20)
 public String getUserpassword() {
  return this.userpassword;
 }

 public void setUserpassword(String userpassword) {
  this.userpassword = userpassword;
 }

}

配置XML  persistence.xml 将其放入META-INF

<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="mysql">
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>

JAVA测试

public static void main(String[]args) throws NamingException{
  Hashtable properties=new Hashtable();
  properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
  properties.put(Context.PROVIDER_URL, "jnp://localhost");
  InitialContext ctx;
  ctx = new InitialContext(properties);
  Usertable user =new Usertable();
  user.setUsername("bbbb");
  user.setUserpassword("bbbb");
  user.setUserid(7);
  UsertableFacadeRemote remote=(UsertableFacadeRemote) ctx.lookup("UsertableFacade/remote");
  //注意在这儿必须使用接口
  //原来这里Calculator   cal=(CalculatorBean)ict.lookup( "CalculatorBean/remote ");
  //应该这样写Calculator   cal=(Calculator)ict.lookup( "CalculatorBean/remote ");
  ///不能强制转化为Bean,应转化为接口
  remote.save(user);
  ctx.close();
 }

JSP测试ENTITY

<%
      Properties prop1=new Properties();
      prop1.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jndi.properties"));
      
      InitialContext ctx1;
      ctx1 = new InitialContext(prop1);
      entity.Usertable user =new entity.Usertable();
   user.setUsername("bbbb");
   user.setUserpassword("bbbb");
   user.setUserid(new Integer(8));
   entity.UsertableFacadeRemote remote=(entity.UsertableFacadeRemote) ctx1.lookup("UsertableFacade/remote");
   //注意在这儿必须使用接口
   //原来这里Calculator   cal=(CalculatorBean)ict.lookup( "CalculatorBean/remote ");
   //应该这样写Calculator   cal=(Calculator)ict.lookup( "CalculatorBean/remote ");
   ///不能强制转化为Bean,应转化为接口
   remote.save(user);
   ctx1.close();
  %>

问题:

Exception   in   thread   "main "   java.lang.ClassCastException:   $Proxy0   cannot   be   cast   to   src.com.liang.CalculatorBean   at   src.com.test.Client.main(Client.java:29)

注意这个错误,//注意在这儿必须使用接口
  //原来这里Calculator   cal=(CalculatorBean)ict.lookup( "CalculatorBean/remote ");
  //应该这样写Calculator   cal=(Calculator)ict.lookup( "CalculatorBean/remote ");
  ///不能强制转化为Bean,应转化为接口

我也尝试了一下,试了个例子,但也出现了这个问题,为什么不能bound呢?
Exception in thread "main" javax.naming.NameNotFoundException: TellerRemote not bound
        at org.jnp.server.NamingServer.getBinding(NamingServer.java:529)
        at org.jnp.server.NamingServer.getBinding(NamingServer.java:537)
        at org.jnp.server.NamingServer.getObject(NamingServer.java:543)
        at org.jnp.server.NamingServer.lookup(NamingServer.java:296)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 

 

我也遇到 “not bound”的问题,解决方法如下:
jndi.properties 文件在这里可以找到:

${jboss.home}/server/all/conf/jndi.properties

或者
${jboss.home}/server/default/conf/jndi.properties
我的配置修改是在 all  目录下的。
最初文本内容是:

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

我做了修改,添加一个参数,修改后如下:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost


重启jboss,运行测试程序,成功。 "not bound"的问题没有出现。
说明:是在本机上做的测试。 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值