In my application, I have an @ApplicationScoped CDI bean to store some information from the database:
@Named
@ApplicationScoped
public class MrBean {
@EJB
private SoyaBean soyaBean;
private List<Toys> myToys;
@PostConstruct
public void prepareMrBean() {
this.myToys = soyaBean.getToys();
}
public void updateToys() {
this.myToys = soyaBean.getToys();
}
}
I also have a AddToy.xhtml page which would simply add a toy to the database. The backing bean is as following:
@Named
@RequestScoped
public class MrsBean {
@EJB
private SoyaBean soyaBean;
@Inject
private MrBean mrBean;
public void addToy() {
this.soyaBean.addToy();
this.mrBean.updateToys();
}
}
Since there is a new toy added to the database, I wanted to update the list of toys in mrBean. However, even though mrsBean called mrBean.updateToys(), the list of toys in mrBean is not updated at all. I have another ViewToys.xhtml with a @RequestScoped backing bean to view the list of toys and I didn’t see the list get updated.
I’d be very grateful if someone could give me an advice on how to tackle this problem.
UPDATE: This is my SoyaBean implementation:
@Stateless
public class SoyaBeanImpl implements SoyaBean {
@PersistenceContext()
private EntityManager em;
@Override
public List<Toys> getToys() {
Query q = em.createQuery("SELECT T from Toys T");
return (List<Toys>) q.getResultList();
}
@Override
public void addToy() {
Toys newToy = new Toys();
em.persist(newToy);
}
}
UPDATE 2 I’d also really appreciate if someone could show me how I can achieve the same goal in any ways other than my troubling way.
Best regards,
James Tran
The problem was that the results of all SQL queries were cached. Hence, even though I tried to refresh the list of toys, it only received the old result. I solved this problem by setting the option
Shared Cache Modein the filepersistence.xmltoNone.I believe not using cache at all is not a good option. Hence, I’d be very grateful if someone could show me how I can achieve the same result without having to turn off cache.