How to write a custom converter for

后端 未结 6 548
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:59

How can I write a custom converter when working with PrimeFaces components that use a list of POJO? My particular problem is with

<         


        
6条回答
  •  臣服心动
    2020-11-29 01:45

    This problem is not primefaces related, just general JSF related.

    Why should you hit the database again? Your bean already contains the list of Objects you want to display in a component, or is it request scoped?

    • Create a Superclass for your Hibernate Pojo's containing an id field. If you don't want to create a super class just use the pojo class, but you need more converter classes.
    • With that Superclass you can create a generic converter for all Pojo Classes containing a list of Pojo's passed in the constructor.
    • Add the converter as a property in your session bean and use that converter in your JSF component.

    If you access the final list via a get property in your bean or the nested one in the converter is of your choice.

    public class SuperPojo
    {
        protected Integer id;
        //constructor & getter
    }
    
    public class PojoTest extends SuperPojo 
    {
        private String label = null;    
        //constructor & getter
    }
    
    public class SuperPojoConverter implements Converter
    {
        private Collection superPojos;
    
        public IdEntityConverter(Collection superPojos)
        {
            this.superPojos = superPojos;
        }
    
        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value)
        {
            //catch exceptions and empty or  null value!
            final int intValue = Integer.parseInt(value);
            for(SuperPojo superPojo : this.superPojos)
                if(superPojo.getId().intValue() == intValue)
                    return superPojo;
    
            return null;
        }
    
        @Override
        public String getAsString(FacesContext context, UIComponent component, Object value)
        {
            //catch null and instanceof
            return String.valueOf(((SuperPojo)value).getId().intValue());
        }
    
        public Collection getSuperPojos()
        {
            return this.superPojos;
        }
    }
    
    public class Bean 
    {
        private SuperPojoConverter pojoTestConverter = null;
    
        public Bean()
        {
            final List pojoTests = //get list from hibernate
            this.pojoTestConverter = new SuperPojoConverter(pojoTests);
        }
    
        public SuperPojoConverter getPojoTestConverter()
        {
            return this.pojoTestConverter;
        }
    }
    
    
    
        
    
    

提交回复
热议问题