Despite it being "commonly discouraged" (by whom?), I'm using something one of the following techniques in my JSF-2.2 backing beans (depending on whether I need personId
for something else):
@ViewScoped
public class BeanConverter {
@Inject @Param(name = "personId")
private ParamValue<Person> curPerson;
}
@ViewScoped
public class BeanConstruct {
@PersistenceContext
private EntityManager em;
@Inject @Param
private ParamValue<Long> personId;
private Person curPerson;
@PostConstruct
public void init() {
curPerson = em.find(Person.class, personId.getValue());
}
}
This uses the excellent CDI support of Omnifaces.
I then use merge()
to update the entity, but in my case only one bean gets to save changes to the entity, so YMMV. When beans need to communicate updates or entity creations among themselves, I usually go for javax.enterprise.Event
s where the event gets the entity as a constructor argument:
public class BeanSending {
@Inject
private Event<PersonCreated> personCreatedEvent;
public void constructPerson() {
Person person = makePerson();
personCreatedEvent.fire(new PersonCreated(person));
}
}
public class BeanUpdater {
public void updatePerson(@Observes PersonCreated evt) {
doStuffWithPerson(evt.getPerson());
}
}