public void setFirst(String first) { this.first = first; }
public String getLast() { return last; }
public void setLast(String last) { this.last = last; } }
这个值对象也很简单,和一般的javaBean差不多,但有两个地方需要注重:
1. 这个类实现了java.io.Serializable接口
2. 这个类使用@DependentObject做了注释
StudentDAO.java
package com.kuaff.ejb3.dependent;
import javax.ejb.Remote; import java.util.List;
@Remote
public interface StudentDAO { int create(String first, String last, String grade, String email); Student find(int id); List findByFirstName(String name); List findByLastName(String name); List findByEmail(String email);
public class StudentDAOBean implements StudentDAO { @Inject private EntityManager manager;
public int 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); return student.getId(); }
public Student find(int id) { return manager.find(Student.class, id); }
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); }
public class Client { public static void main(String[] args) throws NamingException { InitialContext ctx = new InitialContext(); StudentDAO dao = (StudentDAO) ctx.lookup(StudentDAO.class.getName()); int id = dao.create("晁","岳攀","8","smallnest@kuaff.com"); dao.create("朱","立焕","6","zhuzhu@kuaff.com"); List list = dao.findByEmail("zhuzhu@kuaff.com"); for(Object o:list) { Student s = (Student)o; System.out.printf("%s %s的email:%s%n",s.getName().getFirst(),s.getName().getLast(),s.getEmail()); } } }