【发布时间】:2011-12-21 12:18:31
【问题描述】:
我有一个名为“操作”的实体:
@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 是一个 ManagedBean,它有一个 sessionScope,它有一个 product,这是我的实体。该产品包含一个operation,所以是这样的:
(字母c有控制的意思,我的实体产品相关的所有操作都应该由这个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
为什么会这样?
【问题讨论】: