【发布时间】:2011-08-03 08:42:00
【问题描述】:
我有这个服务 bean:
@Stateless
public class BookService
{
@PersistenceContext(unitName="persistentUnit")
protected EntityManager entityManager;
public BookModel find(Long id) {
return entityManager.find(BookModel.class, id);
}
}
Facelet 页面的支持 bean 是:
@ManagedBean(name = "bookBean")
@RequestScoped
public class BookBean implements Serializable
{
@EJB
private BookService bookService;
@ManagedProperty(value="#{param.id}")
private Long id;
private DataModel<BookModel> books;
private BookModel currentBook;
@PostConstruct
public void init() {
if (id == null) {
// UPDATE: Retrieve a list of books.
} else {
// UPDATE: id shouldn't be null here.
// Get detail info about a book using the id
currentBook = bookService.find(id);
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BookModel getCurrentBook() {
return currentBook;
}
public void setCurrentBook(BookModel currentBook) {
this.currentBook = currentBook;
}
}
为什么id的值总是返回null,即使URL返回为bookedit.jsf?id=5418我不明白这个。
另外,我发现EntityManager#find 方法非常严格,因为它只接受主键值作为第二个参数。如果我想传递一个 [hashed] 值而不是主键怎么办。如何使用EntityManager#find 方法做到这一点?
附:我注意到EntityManager#find 的要求对于 OpenJPA 和 EclipseLink 实现是相同的。嗯……
【问题讨论】:
-
您正在尝试在@PostConstruct 中使用注入值。我不确定首先会发生什么——@ManagedProperty 注入或@PostConstruct。你检查了吗?
-
@Osw:
@PostConstruct在所有依赖注入之后运行,所以这部分没问题。 -
@BalusC:根据 DI 和
@PostContruct的文档,您是正确的。不过,我不确定为什么我得到null而不是5148。很奇怪! -
代码看起来不错。这可能是一个错字或一些疏忽。我将开始在构造函数/postconstruct 中调试请求参数映射。探索
ExternalContext#getRequestParameterMap()以查看参数是否存在。 -
真的可以使用#{param.id}来引用参数吗?您不必将参数绑定到 managedbean 的属性并从那里读取吗?
标签: jsf-2 ejb-3.0 jpa-2.0 glassfish-3