javax.ejb.Remote;
import java.util.List;
@Remote
public interface StudentDAO
{
void create(String first, String last, String grade, String email);
Student find(Name name);
List findByFirstName(String name);
List findByLastName(String name);
List findByEmail(String email);
void merge(Student s);
}
StudentDAOBean.java
package com.kuaff.ejb3.composite;
import java.util.List;
import javax.ejb.EntityManager;
import javax.ejb.Inject;
import javax.ejb.Stateless;
@Stateless
public class StudentDAOBean implements StudentDAO
{
@Inject
private EntityManager manager;
public void create(String first, String last, String grade, String email)
{
Student student = new Student();
student.setName(new Name(first,last));
student.setGrade(grade);
student.setEmail(email);
manager.create(student);
}
public Student find(Name name)
{
return manager.find(Student.class, name);
}
public List findByFirstName(String name)
{
return manager.createQuery("from Student s where s.name.last = :name").setParameter("name", name).listResults();
}
public List findByLastName(String name)
{
return manager.createQuery("from Student s where s.name.first = :name").setParameter("name", name).listResults();
}
public List findByEmail(String email)
{
return manager.createQuery("from Student s where s.email = :email").setParameter("email", email).listResults();
}
public void merge(Student s)
{
manager.merge(s);
}
}
Client.java
package com.kuaff.ejb3.composite;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.List;
public class Client
{
public static void main(String[] args) throws NamingException
{
InitialContext ctx = new InitialContext();
StudentDAO dao = (StudentDAO) ctx.lookup(StudentDAO.class.getName());
dao.create("晁","岳攀","8","smallnest@kuaff.com");
dao.create("朱","立焕","6","zhuzhu@kuaff.com");
Name name = new Name("朱","立焕");
//List list = dao.findByEmail("zhuzhu@kuaff.com");
Student s = dao.find(name);
System.out.printf("%s %s的email:%s%n",s.getName().getFirst(),s.getName().getLast(),s.getEmail());
/*
for(Object o:list)
{
Student s = (Student)o;
System.out.printf("%s %s的email:%s%n",s.getName().getFirst(),s.getName().getLast(),s.getEmail());
}
*/
}
}
这个客户端用来测试。
请运行{$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。 |