java 重复注释错误 - 但在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47019186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:28:47  来源:igfitidea点击:

Duplicate annotation error - but where?

javajpaannotations

提问by j4nd3r53n

Briefly, first - I get this Exception message:

简而言之,首先 - 我收到此异常消息:

serverError: class javax.faces.el.EvaluationException Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)

My code consist of 1 Entity class for a table, an EJB, a 'business class' and a JSF page; the exception happens when I call EntityManager.merge(). There is only 1 annotation with 'max = 128' in it:

我的代码包含 1 个表的实体类、一个 EJB、一个“业务类”和一个 JSF 页面;当我调用 EntityManager.merge() 时发生异常。其中只有 1 个带有 'max = 128' 的注释:

@Size(max = 128)
@Column(name = "name")
private String name;

The only place with duplicated annotations is:

唯一有重复注释的地方是:

@Entity
@Table(name = "attributes", schema = "office_db")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
    @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
    @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name"),
    @NamedQuery(name = "Attributes.findByType", query = "SELECT a FROM Attributes a where a.type.id = :type")
})

but I think that should be legit as it has been generated by Netbeans 8.2 from the database table.

但我认为这应该是合法的,因为它是由 Netbeans 8.2 从数据库表中生成的。

Now some more details. First the table:

现在有更多细节。先上表:

mysql> show create table attributes\G
*************************** 1. row ***************************
       Table: attributes
Create Table: CREATE TABLE `attributes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent` int(11) DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `name` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent_ix` (`parent`),
  KEY `type_ix` (`type`),
  CONSTRAINT `attributes_parent_fk` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
  CONSTRAINT `attributes_type_fk` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1301 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
1 row in set (0.03 sec)

Next the Entity class:

接下来是实体类:

import (...stuff...)

@Entity
@Table(name = "attributes")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM     Attributes a"),
    @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
    @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name"),
    @NamedQuery(name = "Attributes.findByType", query = "SELECT a FROM Attributes a where a.type.id = :type")
})
public class Attributes implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Size(max = 128)
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "parent")
    private Collection<Attributes> attributesCollection;
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private Attributes parent;
    @OneToMany(mappedBy = "type")
    private Collection<Attributes> attributesCollection1;
    @JoinColumn(name = "type", referencedColumnName = "id")
    @ManyToOne
    private Attributes type;
    private static final Logger logger=
            Logger.getLogger(Attributes.class.getName());

    public Attributes() {
    }

    public Attributes(Integer id) {
        this.id = id;
    }
    public Attributes(Integer id, Integer parent, Integer type, String name) {
        logger.info("OFFICE Attributes constructor 3 id: "+id+", parent:     "+parent+", type: "+type+", name: "+name);
        this.parent=new Attributes();
        this.type=new Attributes();
        this.id = id;
        this.parent.setId(parent);
        this.type.setId(type);
        this.name = name;
    }

    public Attributes(Integer parent, Integer type, String name) {
        logger.info("OFFICE Attributes constructor 4 parent: "+parent+", type: "+type+", name: "+name);
        this.parent=new Attributes();
        this.type=new Attributes();
        this.parent.setId(parent);
        this.type.setId(type);
        this.name = name;
        logger.info("OFFICE Attributes constructor 4a");
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlTransient
    public Collection<Attributes> getAttributesCollection() {
        return attributesCollection;
    }

    public void setAttributesCollection(Collection<Attributes> attributesCollection) {
        this.attributesCollection = attributesCollection;
    }

    public Attributes getParent() {
        return parent;
    }

    public void setParent(Attributes parent) {
        this.parent = parent;
    }

    @XmlTransient
    public Collection<Attributes> getAttributesCollection1() {
        return attributesCollection1;
    }

    public void setAttributesCollection1(Collection<Attributes> attributesCollection1) {
        this.attributesCollection1 = attributesCollection1;
    }

    public Attributes getType() {
        return type;
    }

    public void setType(Attributes type) {
        this.type = type;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Attributes)) {
            return false;
        }
        Attributes other = (Attributes) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "docdb.Attributes[ id=" + id + " ]";
    }
}

The EJB or session class:

EJB 或会话类:

import (...stuff...)

@Stateless
public class AttributesSession {
    @PersistenceContext(unitName ="officePU")
    private EntityManager em;
    private static final Logger logger=
            Logger.getLogger(AttributesSession.class.getName());

    public List<Attributes>findAttributes(){
        TypedQuery<Attributes> query=
                    em.createNamedQuery("Attributes.findAll",Attributes.class);
        return query.getResultList();
    }

    public Attributes findAttributeById(Long id){
        TypedQuery<Attributes> query=
                em.createNamedQuery("Attributes.findById", Attributes.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public Integer findChildCount(Long id){
        TypedQuery<Integer> query=em.createNamedQuery("findChildCount",Integer.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public String createAttributes(Attributes attr){
        String msg="";

        try{
            em.merge(attr);
            em.flush();
        }
        catch (PersistenceException e){
            msg=e.getMessage();
        }
        return msg;
    }

    public String deleteAttributes(Attributes attr){
        String msg = "";

        try{
            em.remove(em.merge(attr));
            em.flush();
        }
        catch (PersistenceException e){
            msg=e.getMessage();
        }
        return msg;
    }
}

The business or controller class:

业务或控制器类:

import (...stuff...)

@Named(value = "attributesController")
@SessionScoped
public class AttributesController implements Serializable{
    @EJB private AttributesSession sess;
    private Attributes attr;
    private List<Attributes> attrList;
    private Integer id;
    private Integer parent;
    private Integer type;
    private String name;
    private String errmsg;
    private static final Logger logger=
            Logger.getLogger(AttributesController.class.getName());

    public AttributesController() {
        this.attrList = new ArrayList<>();
        this.attr = new Attributes();
    }

    public List<Attributes> getAttrList() {
        return attrList;
    }

    public List<Attributes> getAttrValueList() {
        return attrList;
    }

    ...getters and setters...

    public void clearForm(){
        this.id=null;
        this.name=null;
        this.parent=null;
        this.type=null;
        this.errmsg=null;
    }

    public String createAttributes(){
        if (this.id!=null){
            attr=new Attributes(this.id,this.parent,this.type,this.name);
        }
        else{
            attr=new Attributes(this.parent,this.type,this.name);
        }
        errmsg=sess.createAttributes(attr);
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    public String deleteAttributes(){
        if (this.id!=null){
            attr=new Attributes(this.id,this.parent,this.type,this.name);
            errmsg=sess.deleteAttributes(attr);
        }
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    public String listAttributes(){
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    @PostConstruct
    public void updateList(){
        attrList=sess.findAttributes();
    }

    @Override
    public String toString(){
        return "Name: "+((name==null)?"":name)
                +", parent: "+((parent==null)?"":parent)
                +", type:"+((type==null)?"":type);
    }
}

Finally, the stack trace:

最后,堆栈跟踪:

[2017-10-31T10:23:31.697+0000] [glassfish 5.0] [WARNING] [] [javax.enterprise.resource.webcontainer.jsf.lifecycle] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411697] [levelValue: 900] [[
  #{attributesController.createAttributes()}: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
javax.faces.FacesException: #{attributesController.createAttributes()}: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        ...(deleted stuff)
        ... 35 more
Caused by: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        ... (stuff deleted)
        at docdb.__EJB31_Generated__AttributesSession__Intf____Bean__.createAttributes(Unknown Source)
        at docdb.AttributesController.createAttributes(AttributesController.java:118)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at javax.el.ELUtil.invokeMethod(ELUtil.java:304)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:535)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
        at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
        at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
        at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
        at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
        ... 36 more
]]

[2017-10-31T10:23:31.700+0000] [glassfish 5.0] [INFO] [] [docdb.LifeCycleListener] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411700] [levelValue: 800] [[
  OFFICE END PHASE INVOKE_APPLICATION 5]]

[2017-10-31T10:23:31.701+0000] [glassfish 5.0] [INFO] [] [docdb.LifeCycleListener] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411701] [levelValue: 800] [[
  OFFICE]]

[2017-10-31T10:23:31.703+0000] [glassfish 5.0] [SEVERE] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411703] [levelValue: 1000] [[
  javax.faces.el.EvaluationException: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
        at javax.faces.component.UICommand.broadcast(UICommand.java:330)
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:870)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1418)
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
        at org.glassfish.grizzly.filterchain.ExecutorResolver.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access0(WorkerThreadIOStrategy.java:56)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        at sun.reflect.annotation.TypeAnnotationParser.mapTypeAnnotations(TypeAnnotationParser.java:361)
        at sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl.<init>(AnnotatedTypeFactory.java:139)
        at sun.reflect.annotation.AnnotatedTypeFactory.buildAnnotatedType(AnnotatedTypeFactory.java:65)
        at sun.reflect.annotation.TypeAnnotationParser.buildAnnotatedType(TypeAnnotationParser.java:79)
        at java.lang.reflect.Field.getAnnotatedType(Field.java:1159)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findCascadingMetaData(AnnotationMetaDataProvider.java:610)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findPropertyMetaData(AnnotationMetaDataProvider.java:231)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getFieldMetaData(AnnotationMetaDataProvider.java:220)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.retrieveBeanConfiguration(AnnotationMetaDataProvider.java:128)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfiguration(AnnotationMetaDataProvider.java:119)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanConfigurationForHierarchy(BeanMetaDataManager.java:220)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.createBeanMetaData(BeanMetaDataManager.java:187)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.lambda$getBeanMetaData
@Column(name = "name", length = 128)
private String name;
(BeanMetaDataManager.java:160) at org.hibernate.validator.internal.metadata.BeanMetaDataManager$$Lambda/1020030882.apply(Unknown Source) at java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:324) at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanMetaData(BeanMetaDataManager.java:159) at org.hibernate.validator.internal.engine.ValidatorImpl.getConstraintsForClass(ValidatorImpl.java:308) at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.isBeanConstrained(BeanValidationListener.java:158) at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:108) at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.preUpdate(BeanValidationListener.java:94) at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:726) at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:696) at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:233) at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:87) at org.eclipse.persistence.descriptors.changetracking.AttributeChangeTrackingPolicy.calculateChangesForExistingObject(AttributeChangeTrackingPolicy.java:48) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:711) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1566) at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3256) at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:355) at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158) at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68) at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452) at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854) at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:723) at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4600) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2108) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2078) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88) at com.sun.proxy.$Proxy175.createAttributes(Unknown Source) at docdb.__EJB31_Generated__AttributesSession__Intf____Bean__.createAttributes(Unknown Source) at docdb.AttributesController.createAttributes(AttributesController.java:118) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at javax.el.ELUtil.invokeMethod(ELUtil.java:304) at javax.el.BeanELResolver.invoke(BeanELResolver.java:535) at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256) at com.sun.el.parser.AstValue.invoke(AstValue.java:285) at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304) at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40) at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87) ... 36 more ]]

回答by MartinByers

I would be incredible surprised if the @NamedQueriesis a issue, the name suggests that it should be a list/array of @NamedQueryitems.

如果这@NamedQueries是一个问题,我会非常惊讶,顾名思义,它应该是一个@NamedQuery项目列表/数组。

Try:

尝试:

<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
</dependency>

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Seeing as you are confidant that you don't actually have @sizerepeated, maybe we should be looking at overlap of function, the @Columnannotation contains the same functionality, maybe this could be causing a conflict.

看到您确信您实际上没有@size重复,也许我们应该查看功能重叠,@Column注释包含相同的功能,也许这可能会导致冲突。

回答by Dieudonné

I get the same issue but my problem was comming from pom.xml file. I had there two jpa dependencies

我遇到了同样的问题,但我的问题来自 pom.xml 文件。我有两个 jpa 依赖项

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
    <version>2.5.2</version>
    <scope>provided</scope>
</dependency>

I deleted the first one and this solved my problem. Sorry for my english level

我删除了第一个,这解决了我的问题。对不起我的英语水平

回答by Tatenda Zifudzi

The answers in here already discuss the possible solutions to solve this problem so I will focus on sharing my findings on the root cause of the issue.

此处的答案已经讨论了解决此问题的可能解决方案,因此我将重点分享我对问题根本原因的发现。

I experienced this issue after generating entities using Netbeans 8.2 with the Create Persistence Unit box ticked. Doing this procedure causes two dependencies to be added to your project in the pom.xmlnamely org.eclipse.persistence.jpa.modelgen.processorand eclipselink.

我在使用 Netbeans 8.2 生成实体并勾选了“创建持久性单元”框后遇到了这个问题。执行此过程会导致将两个依赖项添加到您的项目中,pom.xmlorg.eclipse.persistence.jpa.modelgen.processoreclipselink

These EclipseLink dependencies added to my project had a bug issue that was reported:

添加到我的项目中的这些 EclipseLink 依赖项有一个已报告错误问题

... @Column annotation seem to suddenly not be compatible with other annotations anymore.

... @Column 注释似乎突然不再与其他注释兼容了。

As a result of this bug, you therefore would not be able to use @Column annotation with either @NotNull or @Size.

由于此错误,您将无法将@Column 注释与@NotNull 或@Size 一起使用。

回答by babin souare

In the pom.xmlfile, delete:

pom.xml文件中,删除:

@NotNull
@Size(max = 255)
@Column(name = "user_id", nullable = false, length = 255)
private String userName;

回答by Xstarz

this error exists at IDE level. For example on field userNameannoted as:

此错误存在于 IDE 级别。例如在userName注释为的字段上:

@Column(name = "user_id", nullable = false, length = 255)
private String userName;

will throw the duplicate error triggered by @Sizeand length = 255and most probably if the size validity of user_idis not set in the database; and @NotNulland nullable = falsealso most probably if the not nullableconstraint hasn't been set in the DB. Note that by default NetBeans validates your String fields to length 255on Entity autogeneration if the validity doesn'toriginate from the DB. Correct the error thrown by:

将抛出由@Sizeand触发的重复错误,length = 255并且很可能如果user_id数据库中未设置的大小有效性;并且@NotNullnullable = false也最有可能,如果not nullable约束并未在DB中设置。请注意,默认情况下,如果有效性不是来自数据库,NetBeans 会在实体自动生成时验证字符串字段的长度为255。更正抛出的错误:

@NotNull
@Size(max = 255)
@Column(name = "user_id")
private String userName;

OR

或者

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
    <version>2.7.4</version>
    <scope>provided</>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.5.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Edit: For spring-boot users, error could be common if you have both eclipse-link and spring-data-jpa defined in your pom.xml. exclude eclipse-link in your dependencies

编辑:对于 spring-boot 用户,如果在 pom.xml 中同时定义了 eclipse-link 和 spring-data-jpa,则错误可能很常见。在您的依赖项中排除 eclipse-link

回答by MrMins

In my case, I'd the next dependencies:

就我而言,我有下一个依赖项:

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
    <version>2.7.4</version>
    <scope>provided</>
</dependency>

I removed:

我删除了:

##代码##

and now it's working ok.

现在它工作正常。

回答by EstebanBri

I was having the same error, and i solve it removing the @NotNull annotation from the entitiy.

我遇到了同样的错误,我解决了从实体中删除@NotNull 注释的问题。