How to validate if a foreign key entry exists?

大城市里の小女人 提交于 2019-12-01 23:41:32

问题


I have foreign key inside my Customer table.

@JoinColumn(name = "DISCOUNT_CODE", referencedColumnName = "DISCOUNT_CODE")
@ManyToOne(optional = false)
private 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?


回答1:


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!"));
        }
    }
}

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"/>

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.



来源:https://stackoverflow.com/questions/8629550/how-to-validate-if-a-foreign-key-entry-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!