1. ホーム
  2. jsf

[解決済み] javax.validation.ConstraintViolationException

2022-03-04 18:47:01

質問

JSF+JPAを使用していますが、このエラーは修正できません。

javax.validation.ConstraintViolationException: ビーンバリデーション の自動Bean Validationの実行中に制約に違反した。 コールバックイベント:'prePersist'が発生しました。組み込まれた 詳細はConstraintViolationsをご覧ください。

@ManagedBean(name = "clientCon")
public class ClientController {

    @PostConstruct
    public void init() {
        System.out.println("Salam");
        clients = new Clients();
    }

    private EntityManagerFactory emf = null;

    public ClientController() {
        emf = Persistence.createEntityManagerFactory("ClinicProjectPU");
    }

    private List<Clients> clientList;
    private Clients clients;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Clients getClients() {
        return clients;
    }

    public void setClients(Clients clients) {
        this.clients = clients;
    }

    public List<Clients> getClientList() {
        this.clientList = getEntityManager().createNamedQuery("Clients.findAll").getResultList();
        return clientList;
    }

    public void createClient() {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(clients); // the only interesting method
            em.flush();
            em.getTransaction().commit();
            System.out.println("created");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}


<h:form>
    <fieldset>
        <h:panelGrid  columns="2">
            <h:outputText value="Ad" style="color: #0099cc"/>
            <h:inputText class="form-client" value="#{clientCon.clients.name}" />
            <h:outputText  value="Soyad" style="color: #0099cc" />
            <h:inputText class="form-client" value="#{clientCon.clients.surname}" />
            <h:outputText value="Telefon" style="color: #0099cc" />
            <h:inputText class="form-client" value="#{clientCon.clients.phone}" />
        </h:panelGrid>

        <div class="btns">
            <center><h:commandButton action="#{clientCon.createClient()}"  value="Saxla" style="width: 60%;margin-top: 5%;border-radius: 5px;color: #ffffff;background-color: #0099cc" /></center>
        </div>
    </fieldset>
</h:form>


javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4310)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4287)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4229)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
    at controller.ClientController.createClient(ClientController.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:724)

解決方法は?

制約違反の原因を知るために、以下のバリデータとロガーを使用することができます。

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
    
Set<ConstraintViolation<Clients>> constraintViolations = validator.validate(clients);
    
if (constraintViolations.size() > 0 ) {
  System.out.println("Constraint Violations occurred..");
  for (ConstraintViolation<Clients> contraints : constraintViolations) {
    System.out.println(contraints.getRootBeanClass().getSimpleName()+
    "." + contraints.getPropertyPath() + " " + contraints.getMessage());
  }
}

エンティティを永続化する前にロガーを置く。そのため

em.getTransaction().begin();
//here goes the validator
em.persist(clients);

コンパイルして実行します。コンソールには、例外スタックトレースの直前に、どの要素が違反を引き起こしたのかが表示されます。

永続化メソッドを含む try ブロックを ConstraintViolationException (さらなる問題を回避するため、および/または、エラーが発生したこととその理由をユーザーに知らせるため)。しかし、よくできたシステムでは、永続化中に制約違反の例外が発生することはないはずです。JSFや他のMVCフレームワークでは、検証ステップは、サブミット/パーシステンスの前にクライアント側で全体的または部分的に行われなければなりません。これは良い習慣と言えるでしょう。