我有這樣的實體,稱爲「操作」:如何在JSF 2中創建自定義轉換器?
@Entity
@Table(name="operation")
public class Operation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private Integer id;
@NotNull(message="informe um tipo de operação")
private String operation;
//bi-directional many-to-one association to Product
@OneToMany(mappedBy="operation")
private List<Product> products;
// getter and setters
}
我檢索操作是這樣的:(?這可能是通過一個EJB實例,但只是爲了保持它的地方和作爲一個例子,好不好;))
public Map<String, Object> getOperations() {
operations = new LinkedHashMap<String, Object>();
operations.put("Select an operation", new Operation());
operations.put("Donation", new Operation(new Integer(1), "donation"));
operations.put("Exchange", new Operation(new Integer(2), "exchange"));
return operations;
}
所以我試圖讓這個selectOneMenu
所選擇的操作:
的productc
是ManagedBean
具有viewScope
,productb
是一個sessionScope
具有product
這是我的實體ManagedBean。該產品contais一個operation
,所以是這樣的:
(信Ç擁有控制權,其中涉及關於我的實體產品的所有操作都應該由這個bean來處理的意思,好嗎?)
Product productc (ViewScope)
-- ProductBean productb (SessionScope)
---- Product product (Entity)
-------- Operation operation (Entity)
轉換器是一樣的@BalusC是建議前:
@ManagedBean
@RequestScoped
public class OperationConverter implements Converter {
@EJB
private EaoOperation operationService;
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Operation) || ((Operation) value).getId() == null) {
return null;
}
return String.valueOf(((Operation) value).getId());
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || !value.matches("\\d+")) {
return null;
}
Operation operation = operationService.find(Integer.valueOf(value));
System.out.println("Getting the operation value = " + operation.getOperation());
if (operation == null) {
throw new ConverterException(new FacesMessage("Unknown operation ID: " + value));
}
return operation;
}
的日誌中顯示,其中選擇檢索的操作:
FINE: SELECT ID, OPERATION FROM operation WHERE (ID = ?)
bind => [1 parameter bound]
INFO: Getting the operation value = exchange
所以,當我嘗試提交表單給出瞭如下錯誤:
form_add_product:operation: Validation error: the value is not valid
這究竟是爲什麼?