户的方法。
TeacherBean.java
package com.kuaff.ejb3.entity;
import javax.ejb.EntityManager;
import javax.ejb.Inject;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import java.util.Map;
import java.util.Set;
@Stateful
public class TeacherBean implements Teacher
{
@Inject
private EntityManager manager;
private Student student;
public Student getStudent()
{
return student;
}
public void addScore(String studentName, Map<String,Integer> map)
{
if (student == null)
{
student = new Student();
}
student.setName(studentName);
Set<String> set = map.keySet();
for (String sname:set)
{
student.addScores(sname,map.get(sname).intValue());
}
}
@Remove
public void leave()
{
manager.create(student);
}
}
这个是会话Bean的实现类。
Client.java
package com.kuaff.ejb3.entity;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class Client
{
public static void main(String[] args) throws NamingException
{
InitialContext ctx = new InitialContext();
Teacher teacher = (Teacher) ctx.lookup(Teacher.class.getName());
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("语文",new Integer(98));
map.put("化学",new Integer(149));
map.put("物理",new Integer(143));
teacher.addScore("smallnest",map);
Student student = teacher.getStudent();
String name = student.getName();
System.out.printf("显示%s的分数:%n",name);
Collection<Score> c = student.getScores();
for (Score score:c)
{
System.out.printf("%s:%s%n",score.getName(),score.getNumber()+"");
}
}
}
这个客户端增加学生的分数,并且测试显示这个学生的相关信息。
请运行{$JBOSS_HOME}/bin目录下的run.bat: run –c all,启动JBOSS。
http://localhost:8080/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss%3Aservice%3DHypersonic%2Cdatabase%3DlocalDB,然后调用startDatabaseManager()方法,打开HSQL管理工具管理数据库。
在Eclipse的Ant视图中执行ejbjar target。或者在命令行下,进入到此工程目录下,执行ant ejbjar,将编译打包发布此EJB。
在Eclipse的Ant视图中执行run target。或者在命令行下,进入到此工程目录下,执行ant run,测试这个EJB。 |