CDI been creating new record instead of updating - jsf

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?

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.

Related

lazy initialization of CDI injected bean in setter

So I have a bean which contains a category field. If that category field is set to a specific value, for instance "MATCH" I want to initialize a bean. However doing it in the setter of the category is kind of an anti pattern and I'd like to know if in this case that could be considered alright or maybe there is a better way to do it.
I don't want to use postConstruct because the bean is used a really low percentage of the time. So having DB calls in PostConstruct is non sens in my opinion in this case.
#Named
#ViewScoped
public class BeanA implements Serializable {
private Category category;
#Inject
private MatchCreation matchCreation;
public void setCategory(Category category) {
this.category = category;
if("MATCH".equals(category.getName()){
matchCreation.init(); // I'll put a check here to not initialize it twice
}
}
}
#Named
#ViewScoped
public class MatchCreation {
private List<Team> teamList;
private List<Map> mapList;
#EJB
private TeamService ts;
#EJB
private MapService ms;
public void init() {
teamList = ts.getProTeams();
setMapList(ms.getAllMaps());
}
}
Also in that particular bean I have 9 injections. I don't have to be afraid to use those right, I don't have to try to have the bare minimum ?

NullPointerException when trying to access JPA service class

I've the below managed bean
#ManagedBean
#RequestScoped
public class customerBean {
private Customer customer;
private CustomerJpaController customerJpa;
#PostConstruct
public void init() {
customer = new Customer();
}
public String addCustomer() throws Exception {
customerJpa.create(customer);
return "customer";
}
// getter and setter
}
The CustomerJpaController looks like below:
public class CustomerJpaController implements Serializable {
#PersistenceContext(unitName = "JFSCustomerPU")
private EntityManagerFactory emf = null;
private UserTransaction utx = null;
public CustomerJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
// ...
}
When addCustomer() is invoked from the view, it throws java.lang.NullPointerException at line customerJpa.create(customer);. How is this caused and how can I solve it?
In your code sample, your CustomerJpaController is never instantiated. So, you get a null pointer exception.
I advise you to switch to CDI and rely on its injection method to have your entity manager (factory?) properly instantiated and injected in your controller when this last is instantiated. And, so, to use #Named instead of #ManagedBean.
So, you would have :
#Named
#RequestScoped
public class CustomerJpaController implements Serializable {
...
}
(or whichever scope better fits your need)
It seems to me that you should use an EntityManager (EM) rather than an EntityManagerFactory (EMF) in your controller.
If your EMF is container managed and you have only one persistence unit, you can use the standard JPA #PersistenceContext annotation :
#PersistenceContext
private EntityManager entityManager;
If your EMF is not managed, you can leverage the power of deltaspike JPA module (remember : deltaspike is good for you :-) ) and inject an EntityManager in your controller :
#Named
#RequestScoped
public class CustomerJpaController implements Serializable {
#Inject
private EntityManager em;
}
This requires the implementation of an EntityManagerProducer class, which can have any name but must have one method annotated #Produces #RequestScoped returning an EntityManager and another one taking an EntityManager parameter annotated with #Disposes. Ex :
public class MyEntityManagerProducer {
#Inject
#PersistenceUnitName("myPU")
private EntityManagerFactory emf;
#Produces
#RequestScoped
public EntityManager createEntityManager() {
return emf.createEntityManager();
}
public void disposeEntityManager(#Disposes em) {
if (em.isOpen()) {
em.close();
}
}
Note the usage of #PersistenceUnitName("myPU"), the deltaspike annotation that will handle the instanciation of the EMF.
If you have multiple persistence units, as it is often the case in the real world, you can set them apart with qualifiers. To declare a qualifier, declare an #interface with the following annotations :
#Target({ FIELD, METHOD, PARAMETER, TYPE })
#Retention(RUNTIME)
#Documented
#Qualifier
public #interface MyQualifier {
}
Then, add this qualifier to all #Produces, #Disposes and #Inject, to allow CDI to decide which persistence unit / entity manager you are willing to use :
public class MyEntityManagerProducer {
#Inject
#PersistenceUnitName("myPU")
private EntityManagerFactory emf;
#Produces
#MyQualifier
#RequestScoped
public EntityManager createEntityManager() {
return emf.createEntityManager();
}
public void disposeEntityManager(#Disposes #MyQualifier em) {
if (em.isOpen()) {
em.close();
}
}
and in your controller :
#Named
#RequestScoped
public class CustomerJpaController implements Serializable {
#Inject
#MyQualifier
private EntityManager em;
}
All this requires CDI. Configuring CDI is way beyond a short answer to your question. I use OpenWebBeans in all my projects. Weld is also very popular.
This is my understanding of things (it might not be 100% correct but it will give you a general idea) :
Where in your bean is your Service instantiated ? Nowhere. In other words customerJpa is null.
Starting a connection to a db weights a lot on resources. So instead of you instantiating different services by yourself and opening-closing connections, the container has a pool of services and give the free ones to whoever needs it (in your case your bean needs one). How do you ask the container to give you a service :
Annotate #EJB above your service:
#EJB
private CustomerJpaController customerJpa;
and I think you are missing #Stateless as well
#Stateless
public class CustomerJpaController...
It's advised to switch to #Named and #RequestScoped (the other package) instead of #ManagedBean. Then you can use #Inject to inject your service instead of #EJB.here you can read further on the subject.

Why cant I get the value of a SessionScoped bean in the constructor of another bean?

I have this SessionScoped bean:
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable {
/**
* Creates a new instance of LoginBean
*/
public LoginBean() {
this.usuario = new Usuario();
}
private Usuario usuario;
//getter & setter
}
The Usuario class:
public class Usuario {
public Usuario() {
}
private String password;
private String nombre;
private int idPlanta;
private int nivel;
private String idUsuario;
//getters & setters
}
And I want to get the value of the property idPlanta from the SessionScoped bean (LoginBean) here (in the constructor) see the comments:
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
But when I show the value in the view it shows the value that really is in the Session idPlanta = 1. I dont understand why I cant get the value of that property in the constructor of that ViewScoped bean (PrincipalBean). I show the value in the view here(I know I can get it directly fron the LoginBean but this is just to show that the property login in PrincipalBean has the Session value):
<h:outputText class="titulo" value="Bienvenido(a) #{principalBean.login.usuario.nombre} Planta #{principalBean.login.usuario.idPlanta}" />
The value of idPlanta in PrincipalBean is very important because I use it as a method parameter to show more info when the view is showed.
Please help me. I still learning JSF.
You need to be using these values after the bean has been constructed. When your constructor is called, your bean has net yet been initialzed - therefore the injections have not yet happend. Using the #PostConstruct method you will be able to access the desired values from the injected objects.
For example :
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
}
#PostConstruct
public init() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
See Also
Why use #PostConstruct?
Injecting Managed Beans In JSF 2.0
JSF injection with managed property, good pattern?

jsf custom converter does not work with view scope

Here is my code
Pojo
public class Deal implements Serializable {
private int id;
private String name;
private String description;
private Customer customer;
//getter setter omitted
}
public class Customer implements Serializable {
private int id;
private String name;
private String email;
private String phone;
//getter setter and equal hashcode omitted
}
Managed Bean
#ManagedBean(name="dealBean")
#ViewScoped
public class DealBean implements Serializable {
private List<Customer> customerList;
private List<Deal> dealList;
private Deal deal;
#PostConstruct
public void init() {
deal = new Deal();
dealList = new ArrayList<Deal>();
customerList = new ArrayList<Customer>();
customerList.add(new Customer(1, "MPRL", "mprl#mail.com", "1234455"));
customerList.add(new Customer(2, "Total", "total#mail.com", "3434323"));
customerList.add(new Customer(3, "Petronas", "petronas#mail.com", "8989876"));
}
//getter setter omitted
}
Customer Converter
#FacesConverter("customerConverter")
public class CustomerConverter implements Converter {
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String customerID) {
DealBean dealBean = (DealBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dealBean");
if (dealBean != null) {
List<Customer> customerList = dealBean.getCustomerList();
for (Customer customer : customerList) {
if (customerID.equals(String.valueOf(customer.getId()))) {
return customer;
}
}
}
return null;
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
if (obj != null) {
return String.valueOf(((Customer)obj).getId());
}
return null;
}
}
XHTML
Customer : <h:selectOneMenu id="customer" value="#{dealBean.deal.customer}">
<f:converter converterId="customerConverter" />
<f:selectItems value="#{dealBean.customerList}" var="cus"
itemLabel="#{cus.name}" itemValue="#{cus}" />
</h:selectOneMenu>
When the managed bean is in request or session scope, the Customer pojo is set correctly to Deal pojo. The problem is when the managed bean is in View scope, the Customer pojo is set to Deal pojo as NULL.
I am using JSF 2.2.0
Thanks much for the help in advance.
It's not the converter, is the view scoped the one broken:
Since you're using JSF tags, you cannot use #ViewScoped annotation, because it was removed from specification and recovered only for CDI usage. You could use omnifaces view scoped or the components of apache myFaces (I personally recommend omnifaces).
You can confirm this creating a
System.out.print("Creating");
in the constructor and checking how is called each Ajax request, so the bean is not recovered and since is marked as view and is a partial request, the values are not setted again (unless you send all the form, which is not a nice solution), other workaround could be making the bean request and recover all the data each request, making it Session (but will be alive for the session), or the #ConvesationScoped, in which you'll have to destroy and start the conversation manually.
Again, my first recommendation could be change to a Java ee server compliant and use the CDI annotations since JSF are being depreciated and not updated anymore

How to access property of one managed bean in another managed bean

I have a managed bean (SessionScope as follow)
#ManagedBean(name="login")
#SessionScoped
public class Login implements Serializable {
private String userSession;
public Login(){
}
}
In this managedbean, somewhere in the login function, i store the email as a session.
I have another managed bean called ChangePassword (ViewScoped). I need to access the value of the email which is stored in the userSession.
The reason of doing so is that i need to find out the current userSession(email) before i can complete the change password function. (Need change password for that specific email)
How do i do so? New to JSF, appreciate any help!
Just inject the one bean as a managed property of the other bean.
#ManagedBean
#ViewScoped
public class ChangePassword {
#ManagedProperty("#{login}")
private Login login; // +setter (no getter!)
public void submit() {
// ... (the login bean is available here)
}
// ...
}
See also:
Communication in JSF 2.0 - Injecting managed beans in each other
In JSF2, I usually use a method like this:
public static Object getSessionObject(String objName) {
FacesContext ctx = FacesContext.getCurrentInstance();
ExternalContext extCtx = ctx.getExternalContext();
Map<String, Object> sessionMap = extCtx.getSessionMap();
return sessionMap.get(objName);
}
The input parameter is the name of your bean.
if your session scoped bean is like this :
#ManagedBean(name="login")
#SessionScoped
public class Login implements Serializable {
private String userSession;
public Login(){
}
}
you can access the values of this bean like :
#ManagedBean(name="changePassword")
#ViewScoped
public class ChangePassword implements Serializable {
#ManagedProperty(value="#{login.userSession}")
private String userSession;
public ChangePassword (){
}
}
public static Object getSessionObj(String id) {
return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(id);
}
public static void setSessionObj(String id,Object obj){
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(id, obj);
}
Add them in your managed bean :

Resources