如何验证是否存在外键输入? [英] How to validate if a foreign key entry exists?
问题描述
我的Customer
表中有外键.
@JoinColumn(name = "DISCOUNT_CODE", referencedColumnName = "DISCOUNT_CODE")
@ManyToOne(optional = false)
private DiscountCode discountCode;
我有一个包含此表所有字段的表单(包括外键discountCode
及其对另一个表的描述).
I have a form that contains all fields of this table (including the foreign key discountCode
and its description from the other table).
在用户输入外键表中不存在的输入的情况下,我希望能够显示此外键不存在的消息. 当我对该字段进行模糊处理时,我将从表中检索其描述.当用户模糊处理无效字段并且表中不存在该字段时,如何显示错误消息?
I want to be able to show a message that this foreign key does not exist in case that the user entered an input that does not exist in the foreign key table. When I onblur this field, then I'm retriving its description from the table. How can I show the error message of invalid field when the user onblurs it and it does not exist in the table?
推荐答案
您需要的是Validator
.它应该看起来像这样:
What you need is a Validator
. It should look like this:
@ManagedBean
@RequestScoped
public class DiscountCodeValidator implements Validator {
@EJB
private MrBean mrBean;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String discountCode = (String) value;
if (!mrBean.checkDiscountCodeExistence(discountCode)) {
throw new ValidatorException(new FacesMessage("This code is not valid!"));
}
}
}
在您的.xhtml文件中,您可以按以下方式声明此验证器:
In your .xhtml file, you can declare this validator as following:
<h:inputText id="discountCode" value="#{someBean.discountCode}"
validator="#{discountCodeValidator}"
required="true" requiredMessage="Discount code is required.">
<f:ajax event="blur" render="discountMsg" />
</h:inputText>
<h:message for="discountCode" id="discountMsg"/>
要注意的一件事是,我假设您将注入一个EJB以使用checkDiscountCodeExistence()
函数检查折扣代码的存在.因此,我将上述验证器注释为@ManagedBean
.如果不需要注入任何EJB,则可以使用@FacesValidator
注释验证器.
One thing to note is I assume that you would inject an EJB to check the existence of the discount code with the checkDiscountCodeExistence()
function. Hence, I annotated the above Validator as a @ManagedBean
. If you don't need to inject any EJBs, you can annotate the Validator with @FacesValidator
.
这篇关于如何验证是否存在外键输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!