2

我已将我的 JSF manged bean 更改为名为 bean 的 CDI。但是我得到一个奇怪的行为,当我merge()通过 EJB 使用 JPA 更新记录时,正在创建一个新记录而不是更新实体。

我之前的实现

@ManagedBean
@ViewScoped
public class bean implements serializable{
    @EJB Service service;
    private Entity entity;

    @PostConstruct
    private void init(){
         int id = 1;
         this.entity = (Entity) service.findEntity(Entity.class, 1);

    }

    //invoke after editing entity
    public void update(){
         service.update(entity);
    }
}

@Stateless
public class Service implements Serializable{
    @PersistenceContext(unitName="unitName")
    private EntityManager em;    

    public void update(Object obj){
        em.merge(obj);
    }

    public Object find(Class klass, object pk){
        return em.find(klass, pk);
    }

}

结果:实体正在更新

我的新实现

@Named
@ConversationScoped
public class bean implements Serializable{
    //unchanged
}

结果:实体没有被更新,而是创建了一个新记录,除了 id (pk) 之外的所有字段都被复制,因为它是一个自动生成的整数,并且为新记录生成了一个新的 id;为什么会这样?

4

1 回答 1

1

Did you really want to chane the scope of your bean to ConversationScoped. I would have thought that you would use

"javax.faces.view.ViewScoped"

[not javax.faces.bean.ViewScoped!!] and just use @Named. Changing a bean scope changed the whole semantics.

于 2013-11-19T04:35:02.717 回答