I'm trying to improve my usage of the converter, for an autocomplete object into a JSF project. This is my converter:
@FacesConverter(value = "articleColorConverter", forClass = ArticleColor.class)
public class ArticleColorConverter implements Converter {
private ArticleColorDao articleColorDao;
public ArticleColorConverter() {
super();
try {
InitialContext ic = new InitialContext();
articleColorDao = (ArticleColorDao) ic.lookup("java:module/ArticleColorDao");
} catch (NamingException e) {
e.printStackTrace();
}
}
@Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
try {
Long.valueOf(value);
return articleColorDao.findArticleColorByPk(Long.valueOf(value));
} catch (Exception e) {
return null;
}
}
@Override
public String getAsString(FacesContext ctx, UIComponent component, Object value) {
return value.toString();
}
}
And this is entity that:
@Entity public class ArticleColor implements Serializable {
@Id
@GeneratedValue
private Long pk;
private String code;
private String description;
private boolean deleted;
This my toString() method:
Override
public String toString() {
String result = description;
if (code != null) {
result += " (" + code + ")";
}
return result;
}
And finally this is my autocomplete:
<p:autoComplete id="acArticleColor"
value="#{createOrderSelectionView.productionOrder.articleColor}"
completeMethod="#{createOrderSelectionView.completeTextArticleColor}"
style="margin-bottom:10px;" var="articleColor"
itemLabel="#{articleColor}" converter="articleColorConverter"
itemValue="#{articleColor.pk}" forceSelection="true">
</p:autoComplete>
These components works well, but I'm little confusing why should I use the database to retrieve the real from its key, even if I've loaded into the autocomplete the full list of objects. Am I wrong with something?