Search code examples
jsfcdi

CDI been creating new record instead of updating


I have changed my JSF manged bean to a CDI named bean. However I get a strange behavior that when I update a record using JPA merge() through EJB, a new record is being created instead of updating the entity.

my previous implementation

@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);
    }

}

Result: entity is being updated

My new implementation

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

Result: entity is not being updated, and instead a new record is being created with all fields being duplicated except the id (pk) as it is an auto generated integer, and a new id is generated for the new record; Why is this happening?


Solution

  • 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.