Wednesday, August 15, 2018

JSF ManyToMany application tips

Hello,

As many of you know that you can use netbeans in an extremely efficient way to deploy your application entities, backing beans, facade (session beans) and even pages for CRUD operations using "JSF Pages from Entity Classes" or "PrimeFaces Pages frin Entity Classes".

However, this works perfectly when you are using the second (PrimeFaces one) while it doesn't in the first (JSF one).

JSF works well with OneToMany relationships while it doesn't (automatically creating h:selectManyListbox for example) in the ManyToMany relationships. So, you find yourself have to create (h:selectManyListbox) manually and it will not work as you would have the same classic conversion issue from String to List of Objects. In order to get around this you can follow the below simple way.

Create your multiple options control code,

<h:selectManyListbox value="#{furnitureController.materials}">
<f:selectItems value="#{materialController.findAll()}" 
var="c"
itemLabel="#{c.material}" 
itemValue="#{c.id}" />
</h:selectManyListbox >

create the findAll() method in the controller materialController to retrieve the list of the options to you

public List<Material> findAll() {
        return ejbFacade.findAll();
}

Add list of string variable, setter and getter in the controller  furnitureController to hold the primary key values until processing.

private List<String> materials;

    public List<String> getMaterials() {
        return materials;
    }

    public void setMaterials(List<String> materials) {
        this.materials = materials;
    }

Lastly, update the create method with the following code BEFORE the getFacade().create(current);
to loop on the list of IDs and add sub objects to the main object and therefore associate them together in the joined table.

for (String id : materials) {
          current.addMaterial(materialFacade.find(Long.parseLong(id)));
}