2 回答
TA贡献2037条经验 获得超6个赞
最简单的方法是让您的所有JPA实体都从这样的基本实体扩展:
public abstract class BaseEntity<T extends Number> implements Serializable {
private static final long serialVersionUID = 1L;
public abstract T getId();
public abstract void setId(T id);
@Override
public int hashCode() {
return (getId() != null)
? (getClass().getSimpleName().hashCode() + getId().hashCode())
: super.hashCode();
}
@Override
public boolean equals(Object other) {
return (other != null && getId() != null
&& other.getClass().isAssignableFrom(getClass())
&& getClass().isAssignableFrom(other.getClass()))
? getId().equals(((BaseEntity<?>) other).getId())
: (other == this);
}
@Override
public String toString() {
return String.format("%s[id=%d]", getClass().getSimpleName(), getId());
}
}
请注意,拥有一个适当的equals()(和hashCode())很重要,否则您将面临“ 验证错误:值无效”。该Class#isAssignableFrom()测试是避免如Hibernate基于代理失败的测试,而不需要回落到休眠特定Hibernate#getClass(Object)的辅助方法。
并拥有这样的基础服务(是的,我忽略了您使用Spring的事实;这只是给出基本思想):
@Stateless
public class BaseService {
@PersistenceContext
private EntityManager em;
public BaseEntity<? extends Number> find(Class<BaseEntity<? extends Number>> type, Number id) {
return em.find(type, id);
}
}
并实现转换器如下:
@ManagedBean
@ApplicationScoped
@SuppressWarnings({ "rawtypes", "unchecked" }) // We don't care about BaseEntity's actual type here.
public class BaseEntityConverter implements Converter {
@EJB
private BaseService baseService;
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (modelValue instanceof BaseEntity) {
Number id = ((BaseEntity) modelValue).getId();
return (id != null) ? id.toString() : null;
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
try {
Class<?> type = component.getValueExpression("value").getType(context.getELContext());
return baseService.find((Class<BaseEntity<? extends Number>>) type, Long.valueOf(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid ID of BaseEntity", submittedValue)), e);
}
}
}
请注意,它被注册为@ManagedBean而不是@FacesConverter。这个技巧可以让您通过例如在转换器中注入服务@EJB。另请参见如何在@FacesConverter中注入@ EJB,@ PersistenceContext,@ Inject,@ Autowired等?因此,您需要引用converter="#{baseEntityConverter}"而不是converter="baseEntityConverter"。
如果您碰巧将此类转换器更多地用于UISelectOne/ UISelectMany组件(<h:selectOneMenu>和朋友),您可能会发现OmniFaces SelectItemsConverter更加有用。它基于可用的值进行转换,<f:selectItems>而不是每次都进行(可能很昂贵)DB调用。
添加回答
举报