Java Spring Data JPA-“找不到类型的属性”异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19583540/
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
Spring Data JPA - "No Property Found for Type" Exception
提问by Jomoos
Well, I searched Google and found many results, but none of them was able to answer my problem. So, here it goes.
好吧,我搜索了谷歌并找到了很多结果,但没有一个能够回答我的问题。所以,它来了。
I am trying to study Spring MVC and Spring Data JPA by doing a minimal implementation of pinterest clone. So, following is the parts of code which I think is relevant to my problem.
我正在尝试通过对 pinterest 克隆进行最小实现来研究 Spring MVC 和 Spring Data JPA。因此,以下是我认为与我的问题相关的代码部分。
Models/Entities
模型/实体
@Entity
@Table(name = "pin_item")
public class PinItem implements Serializable {
// properties ...
@JoinColumn(name = "board_id", referencedColumnName = "user_board_id")
@ManyToOne(optional = false)
private UserBoard board;
// getters and setters...
}
@Entity
@Table(name = "user_board")
public class UserBoard implements Serializable {
// properties ...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "board")
private List<PinItem> pinItemList;
// getters and setters...
}
Service
服务
@Service
@Transactional(readOnly = true)
public class BoardServiceImpl implements BoardService {
@Autowired
private UserBoardRepository boardRepository;
@Override
public List<UserBoard> findLatestBoards() {
PageRequest request = new PageRequest(
0, PresentationUtil.PAGE_SIZE,
Sort.Direction.DESC, "boardId"
);
return boardRepository.findAll(request).getContent();
}
// Other Methods
}
Repository
存储库
public interface UserBoardRepository extends JpaRepository<UserBoard, Integer> {
}
Now, when I call the findLatestBoards
method in BoardService
, "No Property Found" exception is thrown on the line return boardRepository.findAll(request).getContent();
. Here is the excerpt from tomcat log.
现在,当我调用 中的findLatestBoards
方法时BoardService
,在线上抛出“未找到属性”异常return boardRepository.findAll(request).getContent();
。这是tomcat日志的摘录。
DEBUG LOG
调试日志
12:28:44,254 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'findLatestBoards' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,254 DEBUG JpaTransactionManager:366 - Creating new transaction with name [com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,254 DEBUG JpaTransactionManager:369 - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,255 DEBUG AbstractTransactionImpl:158 - begin
12:28:44,255 DEBUG LogicalConnectionImpl:212 - Obtaining JDBC connection
12:28:44,255 DEBUG DriverManagerDataSource:162 - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/pic_pin]
12:28:44,266 DEBUG LogicalConnectionImpl:218 - Obtained JDBC connection
12:28:44,267 DEBUG JdbcTransaction:69 - initial autocommit status: true
12:28:44,267 DEBUG JdbcTransaction:71 - disabling autocommit
12:28:44,267 DEBUG JpaTransactionManager:401 - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@370da60e]
12:28:44,274 DEBUG TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource:286 - Adding transactional method 'findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
12:28:44,274 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'transactionManager'
12:28:44,274 DEBUG JpaTransactionManager:332 - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] for JPA transaction
12:28:44,274 DEBUG JpaTransactionManager:471 - Participating in existing transaction
12:28:44,279 DEBUG CachedIntrospectionResults:159 - Not strongly caching class [java.io.Serializable] because it is not cache-safe
12:28:44,281 DEBUG JpaTransactionManager:851 - Participating transaction failed - marking existing transaction as rollback-only
12:28:44,281 DEBUG JpaTransactionManager:559 - Setting JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] rollback-only
12:28:44,283 DEBUG JpaTransactionManager:844 - Initiating transaction rollback
12:28:44,284 DEBUG JpaTransactionManager:534 - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194]
12:28:44,284 DEBUG AbstractTransactionImpl:203 - rolling back
12:28:44,284 DEBUG JdbcTransaction:164 - rolled JDBC Connection
12:28:44,285 DEBUG JdbcTransaction:126 - re-enabling autocommit
12:28:44,285 DEBUG JpaTransactionManager:594 - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@75284194] after transaction
12:28:44,285 DEBUG EntityManagerFactoryUtils:338 - Closing JPA EntityManager
12:28:44,286 DEBUG LogicalConnectionImpl:232 - Releasing JDBC connection
12:28:44,286 DEBUG LogicalConnectionImpl:250 - Released JDBC connection
12:28:44,287 DEBUG ExceptionHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,289 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,290 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public java.lang.String com.tecnooc.picpin.controller.BoardController.latest(javax.servlet.http.HttpSession,org.springframework.ui.Model)]: org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
12:28:44,291 DEBUG DispatcherServlet:959 - Could not complete request
Exception
例外
The exception is "org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
". But, if I understood correctly, the property board
is present in PinItem
and is correctly mapped with mappedBy = "board"
in UserBoard
.
例外是“ org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
”。但是,如果我理解正确的话,该属性board
存在于 inPinItem
并正确映射到mappedBy = "board"
in UserBoard
。
org.springframework.data.mapping.PropertyReferenceException: No property board found for type com.tecnooc.picpin.model.UserBoard
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:353)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:271)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:245)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:408)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:372)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:456)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:437)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:319)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:289)
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 org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy147.findAll(Unknown Source)
at com.tecnooc.picpin.service.impl.BoardServiceImpl.findLatestBoards(BoardServiceImpl.java:45)
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 org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy148.findLatestBoards(Unknown Source)
at com.tecnooc.picpin.controller.BoardController.latest(BoardController.java:31)
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 org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I don't get why this exception is thrown. Any idea why it is happening?
我不明白为什么会抛出这个异常。知道为什么会这样吗?
Note:I am using Hibernate as Persistence provider. Also, the code portion I put here is what I thought is relevant to the problem. If it is not, let me know and I will update the question with required portion.
注意:我使用 Hibernate 作为持久化提供者。另外,我放在这里的代码部分是我认为与问题相关的部分。如果不是,请告诉我,我会用所需的部分更新问题。
回答by Andrei I
In JPA a relationship has a single owner, and by using mappedBy
in your UserBoard
class you tell that PinItem
is the owner of that bidirectional relationship, and that the property in PinItem
of the relationship is named board
.
在 JPA 中,关系只有一个所有者,通过mappedBy
在您的UserBoard
类中使用,您可以告诉它PinItem
是该双向关系的所有者,并且该关系的属性PinItem
名为board
。
In your UserBoard
class you do not have any fields/properties with the name board
, but it has a property pinItemList
, so you might try to use that property instead.
在您的UserBoard
班级中,您没有任何带有 name 的字段/属性board
,但它有一个 property pinItemList
,因此您可以尝试使用该属性。
回答by oak
this error happens if you try access un-exists property
如果您尝试访问 un-exists 属性,则会发生此错误
my guess is that sorting is done by spring by property name
and not by real column name
.
and the error indicates that, in "UserBoard"
there is no property named "boardId"
.
我的猜测是排序是由 spring byproperty name
而不是 by 完成的real column name
。并且错误表明,"UserBoard"
没有名为"boardId"
.
bests,
最好的,
Oak
橡木
回答by Alan B. Dee
I ran into this same issue and found the solution here: https://dzone.com/articles/persistence-layer-spring-data
我遇到了同样的问题,并在这里找到了解决方案:https: //dzone.com/articles/persistence-layer-spring-data
I had renamed an entity property. But with Springs Automatic Custom Queries there was an interface defined for the old property name.
我重命名了一个实体属性。但是对于 Springs Automatic Custom Queries,有一个为旧属性名称定义的接口。
public interface IFooDAO extends JpaRepository< Foo, Long >{
Foo findByOldPropName( final String name );
}
The error indicated that it could no longer find "OldPropName" and threw the exception.
该错误表明它无法再找到“OldPropName”并抛出异常。
To quote the article on DZone:
引用 DZone 上的文章:
When Spring Data creates a new Repository implementation, it analyzes all the methods defined by the interfaces and tries to automatically generate queries from the method name. While this has limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort. For example, if the managed entity has a name field (and the Java Bean standard getter and setter for that field), defining the findByName method in the DAO interface will automatically generate the correct query:
当 Spring Data 创建一个新的 Repository 实现时,它会分析接口定义的所有方法,并尝试根据方法名称自动生成查询。虽然这有局限性,但它是一种非常强大且优雅的方式,可以轻松定义新的自定义访问方法。例如,如果托管实体有一个名称字段(以及该字段的 Java Bean 标准 getter 和 setter),则在 DAO 接口中定义 findByName 方法将自动生成正确的查询:
public interface IFooDAO extends JpaRepository< Foo, Long >{
Foo findByName( final String name );
}
This is a relatively simple example; a much larger set of keywords is supported by query creation mechanism.
这是一个相对简单的例子;查询创建机制支持更大的关键字集。
In the case that the parser cannot match the property with the domain object field, the following exception is thrown:
在解析器无法将属性与域对象字段匹配的情况下,抛出以下异常:
java.lang.IllegalArgumentException: No property nam found for type class org.rest.model.Foo
回答by Zane XY
Your naming is not correct.
你的命名不正确。
As per the documentation, if your repository is UserBoardRepository
, the implementation of your custom repository should be name as UserBoardRepositoryImpl
, here you named it as BoardServiceImpl
, that's why it throws the exception.
根据文档,如果您的存储库是UserBoardRepository
,则自定义存储库的实现应该是 name as UserBoardRepositoryImpl
,在这里您将其命名为 as BoardServiceImpl
,这就是它抛出异常的原因。
回答by horizon7
In my case I had a typo (camel case) in my method name. I named it to "findbyLastName" and faced this exception. After I changed it to "findByLastName" exception was gone.
就我而言,我的方法名称中有一个错字(驼峰式大小写)。我将它命名为“findbyLastName”并遇到了这个异常。在我将其更改为“findByLastName”之后,异常消失了。
回答by Abhilash
Since your JPA repository name is UserBoardRepository, your custom Interface name should be UserBoardRepositoryCustom(it should end with 'Custom') and your implementation class name should be UserBoardRepositoryImpl(should end with Impl; you can set it with a different postfix using the repository-impl-postfixproperty)
由于您的 JPA 存储库名称是UserBoardRepository,因此您的自定义接口名称应为UserBoardRepositoryCustom(应以“Custom”结尾),而您的实现类名称应为UserBoardRepositoryImpl(应以 Impl 结尾;您可以使用存储库将其设置为不同的后缀- impl-postfix属性)
回答by Kumar Abhishek
Fixed, While using CrudRepository
of Spring , we have to append the propertyname correctly after findBy otherwise it will give you exception
"No Property Found for Type”
已修复,在使用CrudRepository
Spring 时,我们必须在 findBy 之后正确附加属性名称,否则它会给您异常
“No Property Found for Type”
I was getting this exception as. because property name and method name were not in sync.
我得到了这个例外。因为属性名称和方法名称不同步。
I have used below code for DB Access.
我已将以下代码用于 DB Access。
public interface UserDao extends CrudRepository<User, Long> {
User findByUsername(String username);
and my Domain User has property.
我的域用户有财产。
@Entity
public class User implements UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "userId", nullable = false, updatable = false)
private Long userId;
private String username;
回答by Hyman ZOU
If your project used Spring-Boot ,you can try to add this annotations at your Application.java.
如果您的项目使用 Spring-Boot ,您可以尝试在 Application.java 中添加此注释。
@EnableJpaRepositories(repositoryFactoryBeanClass=CustomRepositoryFactoryBean.class)
@SpringBootApplication
public class Application {.....
回答by avi.elkharrat
Note here: the answers from Zane XY and Alan B. Dee are quite good. Yet for those of you who would use Spring Boot now, and Spring Data, here is what would be a more modern answer.
请注意:Zane XY 和 Alan B. Dee 的回答非常好。然而,对于那些现在会使用 Spring Boot 和 Spring Data 的人来说,这是一个更现代的答案。
Suppose you have a class such as:
假设您有一个类,例如:
@Entity
class MyClass {
@Id
@GeneratedValue
private Long id;
private String myClassName;
}
Now a JpaRepository
for this would look like
现在JpaRepository
这个看起来像
interface MyClassRepository extends JpaRepository {
Collection<MyClass> findByMyClassName(String myClassName);
}
Now your "custom" find bymethod must spelled Collection<MyClass> findByMyClassName(String myClassName)
precisely because Spring needs to have some mechanism to map this method on MyClass
property myClassName
!
现在您的“自定义”查找方法必须Collection<MyClass> findByMyClassName(String myClassName)
准确拼写,因为 Spring 需要有某种机制来将此方法映射到MyClass
属性上myClassName
!
I figured this out because, to me, it seemed natural to find a class by its namesemantically, whereas in fact, synatxicallyyou find by myClassName
我想通了这一点,因为对我来说,这似乎是自然的找到其名称的类语义,而实际上,synatxically你通过myClassName找到
Cheers
干杯
回答by marvin ma
you should receive use page,like this
你应该收到使用页面,像这样
@Override
public Page<UserBoard> findLatestBoards() {
PageRequest request = new PageRequest(
0, PresentationUtil.PAGE_SIZE,
Sort.Direction.DESC, "boardId"
);
return boardRepository.findAll(request).getContent();
}