10
由於JPA 2.0不支持注入EntityListener(JPA 2.1 will),因此決定使用JNDI查找來獲取BeanManager
並通過它獲取登錄用戶。我定義的EntityListener
與此類似:EntityListeners中的CDI注入
public class MyEntityListener {
public static BeanManager getBeanManager() {
try {
InitialContext initialContext = new InitialContext();
return (BeanManager) initialContext.lookup("java:comp/BeanManager");
} catch (NamingException e) {
e.printStackTrace();
return null;
}
}
public Object getBeanByName(String name) {
BeanManager bm = getBeanManager();
Bean bean = bm.getBeans(name).iterator().next();
CreationalContext ctx = bm.createCreationalContext(bean);
return bm.getReference(bean, bean.getClass(), ctx);
}
@PrePersist
@PreUpdate
public void onPreInsertOrUpdate(MyEntity entity) {
User loggedInUser = (User) getBeanByName("loggedInUser");
entity.setUpdatedUser(loggedInUser);
entity.setUpdatedTimestamp(new Date());
}
}
用戶在會話範圍管理爲:
@SessionScoped
public class UserManager implements Serializable {
private User loggedInUser;
@Produces
@Named("loggedInUser")
public User getLoggedInUser() {
return loggedInUser;
}
// Set the logged in user after successfully login action
}
我想知道的是有什麼缺點或分交這種方法的關注。性能吞吐量?當多個登錄用戶在自己的作用域中同時更新實體時會發生什麼?
Hibernate的JPA 2.0
縫焊CDI
Glassfish的3.1.2