为什么entityManager.contains返回不同的结果?

时间:2013-03-21 01:42:40

标签: jpa ejb persistence

这是在JPA2(EclipseLink)和JSF2。

我有一个实体类学生:

@Entity
public class Student implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private int age;

public Student(String firstname, String lastname, int age) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
}

public Student() {
}

// accessors and mutators here

}

继承AbstractFacade的会话bean StudentFacade:

public abstract class AbstractFacade<T> {

private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
    this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity) {
    getEntityManager().persist(entity);
}

public T edit(T entity) {
    return getEntityManager().merge(entity);
}

public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {
    return getEntityManager().find(entityClass, id);
}

// other methods: findAll, findRange, count

}

@Stateless
public class StudentFacade extends AbstractFacade<Student> {

@PersistenceContext(unitName = "jpa2testsPU")
private EntityManager em;

@Override
protected EntityManager getEntityManager() {
    return em;
}

public StudentFacade() {
    super(Student.class);
}

public boolean contains(Student s) {
    return getEntityManager().contains(s);
}

public void testContains() {
    Student s = find(1L);
    boolean isContains = getEntityManager().contains(s);
}

}

这是我的JSF Managed Bean:

@ManagedBean
@RequestScoped
public class IndexController {

@EJB
private StudentFacade studentFacade;

/**
 * Creates a new instance of IndexController
 */
public IndexController() {
}

public String test() {
    Student s = new Student("John", "Doe", 20);
    studentFacade.create(s);

    Student s1 = studentFacade.find(1L); // This works because table only has 1 record
    boolean isContains = studentFacade.contains(s);

    return null;
}
}

当我从托管bean运行test()时,isContains为false。但是当调用StudentFacade中的testContains()时,isContains为true。这是为什么?

1 个答案:

答案 0 :(得分:1)

StudentFacade是无状态会话Bean(SSB)。不保证跨方法调用(reference)保留其实例变量的内容。这就像为每个方法调用创建了一个不同的EntityManager实例。

当您从托管bean运行测试时,您在SSB上调用两个不同的方法,因此为每个调用创建了一个不同的EntityManager实例,而第二个实例不包含Student实例,因为它尚未加载

但是当您在SSB本身的方法中运行测试时,相同的EntityManager将用于整个方法的范围,因此对contains()的调用将返回true。