"FIRST") }),
@DependentAttribute(name = "last", column ={ @Column(name = "LAST") }) })
来声明,并指定这个依赖类的两个属性first和last,并映射到数据表的FIRST和LAST列上。
Name.java
package com.kuaff.ejb3.dependent;
import java.io.Serializable;
import javax.ejb.AccessType;
import javax.ejb.DependentObject;
@DependentObject(access = AccessType.PROPERTY)
public class Name implements java.io.Serializable
{
private String first;
private String last;
public Name()
{}
public Name(String first, String last)
{
this.first = first;
this.last = last;
}
public String getFirst()
{
return first;
}
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);
void merge(Student s);
}
EJB 3.0开发指南之依赖值对象(3)
时间:2009-11-27 天极
这个会话Bean接口提供查找用户的方法。
StudentDAOBean.java
package com.kuaff.ejb3.dependent;
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 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);
}
}
这个是会话Bean的实现类。可以看到根据值对象的属性查找主实体Bean。
Client.java
package com.kuaff.ejb3.dependent;
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());
int id = dao.create("晁","岳攀"
|