【问题标题】:Spring data jpa: required identifier property not found for class ConnectionManagerSpring data jpa:找不到类 ConnectionManager 所需的标识符属性
【发布时间】:2019-10-10 00:00:43
【问题描述】:

尝试通过控制器方法中的 CrudRepository 保存 ConnectionManager 类时,我收到错误“找不到类 ConnectionManager 所需的标识符属性”。

我有一个 ConnectionManager,它与 DocumentDetail 具有一对一的关系,而 DocumentDetail 与 DocumentValidation 具有一对多的关系。

Hibernate 从实体生成架构,我可以在数据库中看到一个 id 字段。在控制台中,这是用于创建 connectionManager 表的日志。

Hibernate:创建表connection_manager(id bigint默认生成为identity,control_id bigint,序列整数不为null,类型varchar(255),document_detail_id bigint,email_detail_id bigint,sql_detail_id bigint,主键(id))

  @Entity
 public class ConnectionManager {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 private Long controlId;

private int sequence;



public enum ValidationType {Email, Document, Sql};
@Enumerated(EnumType.STRING)
private ValidationType type;


@OneToOne

@MapsId
private EmailDetail emailDetail;

@OneToOne
@MapsId
private DocumentDetail documentDetail;

@OneToOne

@MapsId
private SqlDetail sqlDetail;

public ConnectionManager(){};
//getters setters
DocumentDetail

文档详细信息

@Entity
public class DocumentDetail {

 @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(mappedBy= "documentDetail", cascade = CascadeType.PERSIST)
private List<DocumentValidation> documentValidationList;

private String location;

public DocumentDetail(){};
//getters setters
Document Validation

文档验证

@Entity
public class DocumentValidation {


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne
@JoinColumn(name = "documentDetail_id")
private DocumentDetail documentDetail;

private String details;

public DocumentValidation(){}

我创建和保存对象的控制器

@Controller
public class ConnectionManagerController {

@Autowired
ConnectionManagerService connectionManagerService;


@RequestMapping(value = "/testAdd", method = RequestMethod.GET)
public ResponseEntity<ConnectionManager> testAdd() {
DocumentValidation documentValidation1 = new DocumentValidation();
documentValidation1.setDetails("1st validation for document 1");
DocumentValidation documentValidation2 = new DocumentValidation();
documentValidation2.setDetails("2nd validation for document 1");   

ArrayList<DocumentValidation> documentValidationList = new  ArrayList<DocumentValidation>();
documentValidationList.add(documentValidation1);
documentValidationList.add(documentValidation2);

DocumentDetail documentDetail1 = new DocumentDetail();
documentDetail1.setLocation("location of document 1");
documentDetail1.setDocumentValidationList(documentValidationList);

ConnectionManager connectionManager1 = new ConnectionManager();
//connectionManager1.setId((long) 1000);
connectionManager1.setType(ValidationType.Document);
connectionManager1.setDocumentDetail(documentDetail1);
connectionManager1.setControlId((long) 1000);



return new ResponseEntity<ConnectionManager>(connectionManagerService.save(connectionManager1),HttpStatus.OK);

} }

完整的堆栈跟踪

            org.springframework.dao.InvalidDataAccessApiUsageException: Required identifier property not found for class com.mycompany.hibernatepoc.ConnectionManager!; nested exception is java.lang.IllegalStateException: Required identifier property not found for class com.mycompany.hibernatepoc.ConnectionManager!
            at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:370)
            at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
            at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
            at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
            at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
            at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
            at com.sun.proxy.$Proxy165.save(Unknown Source)
            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:498)
            at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
            at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
            at com.sun.proxy.$Proxy165.save(Unknown Source)
            at com.mycompany.hibernatepoc.ConnectionManagerService.save(ConnectionManagerService.java:18)
            at com.mycompany.hibernatepoc.ConnectionManagerController.testAdd(ConnectionManagerController.java:44)
            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:498)
            at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
            at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:645)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
            at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
            at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
            at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at com.mycompany.hibernatepoc.security.jwt.JWTFilter.doFilter(JWTFilter.java:38)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
            at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
            at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
            at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
            at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
            at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
            at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
            at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
            at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
            at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
            at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
            at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
            at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
            at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
            at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
            at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
            at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
            at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
            at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
            at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
            at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
            at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
            at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
            at io.undertow.servlet.handlers.SessionRestoringHandler.handleRequest(SessionRestoringHandler.java:119)
            at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
            at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
            at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
            at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
            at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
            at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
            at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
            at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
            at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
            at io.undertow.server.Connectors.executeRootHandler(Connectors.java:364)
            at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at java.lang.Thread.run(Thread.java:748)
        Caused by: java.lang.IllegalStateException: Required identifier property not found for class com.mycompany.hibernatepoc.ConnectionManager!
            at org.springframework.data.mapping.PersistentEntity.getRequiredIdProperty(PersistentEntity.java:105)
            at org.springframework.data.relational.core.conversion.AggregateChange.lambda$executeWith$0(AggregateChange.java:86)
            at java.util.ArrayList.forEach(ArrayList.java:1257)
            at org.springframework.data.relational.core.conversion.AggregateChange.executeWith(AggregateChange.java:71)
            at org.springframework.data.jdbc.core.JdbcAggregateTemplate.save(JdbcAggregateTemplate.java:104)
            at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.save(SimpleJdbcRepository.java:45)
            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:498)
            at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
            at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
            at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
            at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
            at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
            ... 131 common frames omitted

【问题讨论】:

  • 你为什么要删除另一个问题?按照旧问题的要求:您能告诉我您是如何创建表格的吗?当 Hibernate 创建表时,您是否在日志中看到任何错误?
  • 这是一个不同的问题,我稍微修改了代码,现在它是一个不同的错误,因为之前没有创建 id,现在是。我使用设置 hibernate.hbm2ddl.auto: create。 hibernate 的任何 create 语句都没有错误
  • 你的问题是什么?
  • 尝试通过控制器方法中的 CrudRepository 保存 ConnectionManager 类时,出现错误“找不到类 ConnectionManager 所需的标识符属性”。
  • 你能发布整个堆栈跟踪吗?

标签: hibernate spring-boot spring-data-jpa


【解决方案1】:

问题描述

required identifier property not found for class ConnectionManager

问题解决

@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
//Add this annotation
@org.springframework.data.annotation.Id
private Integer id;

我只是跟踪代码

package org.springframework.data.mapping.model;
public class BasicPersistentEntity{

public void addPersistentProperty(P property) {
        ......
           //Get the property
            P candidate = this.returnPropertyIfBetterIdPropertyCandidateOrNull(property);
            if (candidate != null) {
                this.idProperty = candidate;
            }

            if (property.isVersionProperty()) {
                P versionProperty = this.versionProperty;
                if (versionProperty != null) {
                    throw new MappingException(String.format("Attempt to add version property %s but already have property %s registered as version. Check your mapping configuration!", property.getField(), versionProperty.getField()));
                }

                this.versionProperty = property;
            }

        }
    }

}

@Nullable
protected P returnPropertyIfBetterIdPropertyCandidateOrNull(P property) {
    //This property is BasicRelationalPersistentProperty instance
    if (!**property.isIdProperty()**) {
        return null;
    } else {
        P idProperty = this.idProperty;
        if (idProperty != null) {
            throw new MappingException(String.format("Attempt to add id property %s but already have property %s registered as id. Check your mapping configuration!", property.getField(), idProperty.getField()));
        } else {
            return property;
        }
    }
}

转到 AnnotationBasedPersistentProperty(BasicRelationalPersistentProperty 的超类)

public abstract class AnnotationBasedPersistentProperty{

    public boolean isIdProperty() {
        return (Boolean)this.isId.get();
    }

}

转到 org.springframework.data.util.class 懒惰

public T get() {
    T value = this.getNullable();
    if (value == null) {
        throw new IllegalStateException("Expected lazy evaluation to yield a non-null value but got null!");
    } else {
        return value;
    }
}

@Nullable
private T getNullable() {
    T value = this.value;
    if (this.resolved) {
        return value;
    } else {
        //Look at this code
        value = this.supplier.get();
        this.value = value;
        this.resolved = true;
        return value;
    }
}

返回 AnnotationBasedPersistentProperty

private final Lazy<Boolean> isId = Lazy.of(() -> {
    //Note:This class Id is org.springframework.data.annotation.Id;
    return this.isAnnotationPresent(Id.class);
});

  public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
        return this.doFindAnnotation(annotationType).isPresent();
    }


private <A extends Annotation> Optional<A> doFindAnnotation(Class<A> annotationType) {
    Optional<? extends Annotation> annotation = 
//Note:find the spring.framework.data.annotation.Id in the cache.You can find one
(Optional)this.annotationCache.get(annotationType);
    return annotation != null ? annotation : 
(Optional)this.annotationCache.computeIfAbsent(annotationType, (type) -> {
        return this.getAccessors().map((it) -> {
            return AnnotatedElementUtils.findMergedAnnotation(it, type);
        }).flatMap(StreamUtils::fromNullable).findFirst();
    });
}

如果不添加 spring.framework.data.annotation.Id 'annotationCache'

如果添加 spring.framework.data.annotation.Id 'annotationCache'

我的mvn是

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

希望对你有所帮助^-^

【讨论】:

  • 这是不对的。 JPA 实体使用javax.persistence.Id,它们当然不需要@Id 注释。显然您所说的@Id 是针对non-RDBMs use 的,但由于这是MySQL,它不会有用。
  • 非常感谢!这对我的情况很有帮助:r2dbc-postgres
【解决方案2】:

我认为你混合了你的包裹。 您应该在javax.persistence 中使用@Id。 因此,请验证您的 ConnectionManager 的导入。

【讨论】:

    【解决方案3】:
    1. 检查您是否同时使用spring-boot-starter-data-jpaspring-boot-starter-data-jdbc 或任何类似的依赖项。这可能会在运行时导致歧义。如果您使用 JPA 注释,请尝试仅使用 jpa

    2. 请确保您已配置 JPA 存储库查找。在你的配置类中使用@EnableJpaRepositories("repository package name")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 2021-12-06
      • 2021-06-27
      • 2020-07-15
      • 2019-03-07
      相关资源
      最近更新 更多