JavaEE5学习笔记08-JPA与EJB集成总结(3)

1.       测试代码

部署成功后,在另一个项目中建立测试代码如下

 public class TestJPASessionBean extends TestCase {

 

    static Context context;

 

    public Context init() {

 

       if (context == null) {

           String init_factory = "org.jnp.interfaces.NamingContextFactory";

           String serverURL = "jnp://127.0.0.1:1099";

 

           Properties properties = new Properties();

           properties.put(Context.INITIAL_CONTEXT_FACTORY, init_factory);

 

           properties.put(Context.URL_PKG_PREFIXES,

                  "org.jboss.naming:org.jnp.interfaces");

 

           properties.put(Context.PROVIDER_URL, serverURL);

           try {

              context = new InitialContext(properties);

           } catch (NamingException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }

       }

 

       return context;

    }

 

    public void test01save() throws NamingException {

 

       context = init();

       IPersonEAO personEAO = (IPersonEAO) context

              .lookup("myear/PersonEAO/remote");

       Person person = new Person();

       person.setName("千叶传奇");

       personEAO.save(person);

 

    }

 

    public void test02list() throws NamingException {

       context = init();

       IPersonEAO personEAO = (IPersonEAO) context

              .lookup("myear/PersonEAO/remote");

       List<Person> personList = personEAO.findAll();

       for (Person person : personList) {

           System.out.println("id:" + person.getId() + "-----name:"

                  + person.getName());

       }

    }

 

    public void test03listByCondition() throws NamingException {

       context = init();

       IPersonEAO personEAO = (IPersonEAO) context

              .lookup("myear/PersonEAO/remote");

       Person person = personEAO.findByName("素还真").get(0);

       System.out.println("id:" + person.getId() + "______name:"

              + person.getName());

    }

}

因为sessionBean是部署到ear包中,所以在JNDI查找的时候一定要用名称 myear/PersonEAO/remote才能找到服务对象。本程序执行前数据库如下
JavaEE5学习笔记08-JPA与EJB集成总结(3)
 

执行测试程序后,控制台如下:

id:1-----name:刘岩

id:2-----name:素还真

id:3-----name:叶小钗

id:4-----name:一页书

id:5-----name:剑藏玄

id:6-----name:傲笑红尘

id:7-----name:花风云

id:8-----name:宇文天

id:9-----name:欧阳上智

id:10-----name:欧阳尚智

id:11-----name:史艳文

id:12-----name:史青青

id:13-----name:一线生

id:14-----name:冷剑白狐

id:15-----name:乱世狂刀

id:16-----name:魔魁

id:17-----name:独眼龙

id:18-----name:金太极

id:24-----name:千叶传奇

id:2______name:素还真

红色是 test02list() 方法的结果,蓝色是 test03listByCondition() 的结果。

你可能感兴趣的:(jboss,ejb,jpa)