由于 JPA 2.0 不支持注入 EntityListener(JPA 2.1 将),决定使用 JNDI 查找来获取BeanManager
并通过它获取登录用户。我定义了一个EntityListener
类似的:
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
}
我想知道这种方法有什么缺点或需要注意的地方。性能吞吐量?当有多个登录用户在他们自己的范围内同时更新实体时会发生什么?
休眠 JPA 2.0
缝焊 CDI
Glassfish 3.1.2