我是 JSF 的新手,我一直在尝试从使用 ah:selectOneMenu 获取产品类别的表单中存储数据。h:selectOneMenu 是从数据库中填充的,但是,当尝试将产品存储在数据库中时,我收到一个错误:“null Converter”的转换错误设置值“52”。我已经在 StackOverflow 和在线教程中查看了类似的问题,但我仍然收到错误消息。
这是xhtml:
<h:selectOneMenu id="category_fk" value="#{productController.product.category_fk}"
converter="#{categoryConverter}" title="Category_fk" >
<!-- DONE: update below reference to list of available items-->
<f:selectItems value="#{productController.categoryList}" var="prodCat"
itemValue="#{prodCat}" itemLabel="#{prodCat.name}"/>
</h:selectOneMenu>
这是产品控制器:
@Named
@RequestScoped
public class ProductController {
@EJB
private ProductEJB productEjb;
@EJB
private CategoryEJB categoryEjb;
private Product product = new Product();
private List<Product> productList = new ArrayList<Product>();
private Category category;
private List<Category> categoryList = new ArrayList<Category>();
public String doCreateProduct()
{
product = productEjb.createProduct(product);
productList = productEjb.findAllProducts();
return "listProduct";
}
@PostConstruct
public void init()
{
categoryList = categoryEjb.findAllCategory();
productList = productEjb.findAllProducts();
}
// Getters/Setters and other methods omitted for simplicity
这是为简单起见而简化的 EJB:
@Stateless
public class ProductEJB{
@PersistenceContext(unitName = "luavipuPU")
private EntityManager em;
public List<Product> findAllProducts()
{
TypedQuery<Product> query = em.createNamedQuery("findAllProducts", Product.class);
return query.getResultList();
}
public Product createProduct(Product product)
{
em.persist(product);
return product;
}
}
这是为简单起见简化的产品实体:
@Entity
@NamedQueries({
@NamedQuery(name="findAllProducts", query = "SELECT p from Product p")
})
public class Product implements Serializable
{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy= GenerationType.AUTO)
private int product_id;
private String name;
private String description;
protected byte[] imageFile;
private Float price;
@Temporal(TemporalType.TIMESTAMP)
private Date dateAdded;
@ManyToOne
private Category category_fk;
@ManyToOne
private SaleDetails saleDetails_fk;
这是我正在使用的更新转换器:
@ManagedBean
@FacesConverter(value="categoryConverter")
public class CategoryConverter implements Converter{
@PersistenceContext
private transient EntityManager em;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return em.find(Category.class, new Integer(value));
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
Category category;
category = (Category) value;
return String.valueOf(category.getCategory_id());
}
}
代码已从原始问题更新,代码现在完美运行。