主键自动产生
@Id(generate = GeneratorType.AUTO)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getNumber()
{
return number;
}
public void setNumber(int number)
{
this.number = number;
}
@ManyToOne
@JoinColumn(name = "student_id")
public Student getStudent()
{
return student;
}
public void setStudent(Student student)
{
this.student = student;
}
}
这个实体Bean存放学生的分数。
Teacher.java
package com.kuaff.ejb3.entity;
import javax.ejb.Remote;
import javax.ejb.Remove;
import java.util.Map;
@Remote
public interface Teacher
{
public void addScore(String studentName,Map<String,Integer> map);
public Student getStudent();
@Remove
public void leave();
}
这个会话Bean接口提供增加分数和得到用户的方法。
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);
}
}
EJB 3.0开发指南之实体Bean(5)
时间:2009-11-27 天极
这个是会话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。
|