177

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.

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.

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
    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$1.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$1.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.

Jomoos
  • 12,823
  • 10
  • 55
  • 92
  • 3
    I ran into the same issue when I had named an embedded ID as *MyCompositePK* and tried writing *findByMyCompositePKUserId(Long userId)*. The point is, it needs to be camel case as well for the CRUD repository, so as to differentiate between the table properties when creating the query out of your method. So, it has to be *MyCompositePk* and *findByMyCompositePkUserId(Long userId)* – EmeraldTablet Oct 05 '17 at 16:48
  • In my case the mistake was that I wrote "by" two time. findByApropAndByBprop - mistake. Write "by" once - findByApropAndBprop - correct – lingar Mar 11 '23 at 20:23

30 Answers30

182

I ran into this same issue and found the solution here: 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.

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.

To quote the article on 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:

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
hs-
  • 176
  • 2
  • 5
  • 21
Alan B. Dee
  • 5,490
  • 4
  • 34
  • 29
  • 1
    How did you solve it though? I seem to have done the same thing but I want to refresh those automatic custom queries. How do i do it? Or what file do I need to edit? – peterpie Jun 01 '22 at 15:02
  • 1
    The solution was to rename the old to the new. You could also just define an @Query annotation to enter the query you want it to use. – Alan B. Dee Jun 03 '22 at 15:22
113

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.

Zane XY
  • 2,743
  • 1
  • 22
  • 12
  • 1
    additionally, all repository classes/interfaces should be placed in one directory - as far as I know – Błażej Kocik Nov 30 '17 at 13:01
  • 30
    I don't know why this is upvoted so much, but there is no custom repository involved in this question. `BoardServiceImpl` is just a service using the `UserBoardRepository`. – Didier L Apr 09 '19 at 15:48
  • that's my case! I had no problem before I moved Impl classes in a completely different package, but after that this happened. Thank you – Buckstabue Jun 12 '19 at 10:48
  • 1
    Though this is not the solution to the OP's error, this is another reason why you could be getting the same error message as the OP's title and that's why this answer should be taken in consideration – juan_carlos_yl May 25 '21 at 03:50
  • @BłażejKocik not exactly, the `Impl` can be in a sub package. See https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#repositories.configuration : "*[...] autodetect custom implementation fragments by scanning for classes below the package in which it found a repository.*" – potame Jun 09 '22 at 12:19
56

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”

I was getting this exception as. because property name and method name were not in sync.

I have used below code for 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;
Kumar Abhishek
  • 3,004
  • 33
  • 29
  • 2
    This approach helped me - I used incorrect name of a property of my class in repository's 'default' (provided by CrudRepository interface) method (i.e.instea of findByDateOfStatisticsBetween() I used findByDateBetween() method naming) – ryzhman Nov 05 '17 at 20:15
  • 1
    example `findStatusId` wrong `findByStatusId` correct and for multiple naming check https://stackoverflow.com/a/32796493/944593 – shareef Jun 10 '18 at 23:30
  • Saved a ton of time for me. Thank you :). – vijayakumarpsg587 Dec 03 '18 at 15:10
  • This. In my exp it was naming a method "findByAgeGreaterThanOrEqual" ("or" is not recognized) whereas the expected form is "findByAgeGreaterThanEqual". – nrp Apr 19 '23 at 10:43
38

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-postfix property)

Abhilash
  • 761
  • 7
  • 8
24

this error happens if you try access un-exists property

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

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
oak
  • 2,898
  • 2
  • 32
  • 65
  • Thank you. It took me a while to find this solution because Spring was complaining about something completely different. I have a class `A` and a class `B` that extends `A` and have a property `x`. It was complaining that it couldn't find property `x` in class `A`... – GuiRitter Mar 14 '18 at 11:30
  • Thank you so much. That helped me in a way. I wrote findByUsername instead of findByUserName – Adil Aslam Sachwani Feb 01 '21 at 07:31
16

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.

horizon7
  • 1,113
  • 14
  • 18
10

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.

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

interface MyClassRepository extends JpaRepository {
    Collection<MyClass> findByMyClassName(String myClassName);
}

Now your "custom" find by method must spelled Collection<MyClass> findByMyClassName(String myClassName) precisely because Spring needs to have some mechanism to map this method on MyClass property myClassName!

I figured this out because, to me, it seemed natural to find a class by its name semantically, whereas in fact, synatxically you find by myClassName

Cheers

avi.elkharrat
  • 6,100
  • 6
  • 41
  • 47
9

In my case I had used the wrong column name for sorting while creating the PageRequest object.

PageRequest paging = PageRequest.of(page, 30, Sort.by("column_name")); 

the correct syntax was

PageRequest paging = PageRequest.of(page, 30, Sort.by("columnName")); 

Spring was giving an error 'No property found for type column'. I was looking at the repository and Entity and didn't find anything. The error was at the controller where I had created the PageRequest object.

So the error is thrown when you use wrong semantics but it is not necessary that you have done the mistake at the Repository only.

Praveen Kumar
  • 222
  • 3
  • 6
  • Your answer helped me to solve my issue where I was passing null value for sorting column to my REST API. After passing column name, able to get get data. Thanks. – Ram Jul 28 '22 at 08:34
6

Another scenario, that was not yet mentioned here, that caused this error is an API that receives Pageable (or Sort) and passes it, as is, to the JPA repository when calling the API from Swagger.

Swagger default value for the Pageable parameter is this:

  {
    "page": 0,
    "size": 0,
    "sort": [
      "string"
    ]
  }

Notice the "string" there which is a property that does exist. Running the API without deleting or changing it will cause org.springframework.data.mapping.PropertyReferenceException: No property string found for type ...

selalerer
  • 3,766
  • 2
  • 23
  • 33
  • 1
    This was my issue. My Sort was on a property that I had all uppercase to match the DB, but it needed to be lowercase to match the property on the class, then it all worked. Thanks! – DragonBeer Nov 04 '20 at 18:38
3

it looks like your custom JpaRepository method name does not match any Variable in your entity classs. Make sure your method name matches a variable in your entity class

for example: you got a variable name called "active" and your custom JpaRepository method says "findByActiveStatus" and since there is no variable called "activeStatus" it will throw"PropertyReferenceException"

bubingaa
  • 71
  • 4
2

I had a similiar problem that caused me some hours of headache.

My repository method was:

public List<ResultClass> findAllByTypeAndObjects(String type, List<Object> objects);

I got the error, that the property type was not found for type ResultClass.

The solution was, that jpa/hibernate does not support plurals? Nevertheless, removing the 's' solved the problem:

public List<ResultClass> findAllByTypeAndObject(String type, List<Object>
2

I had this exception recently when moving to a newer spring-boot version (from 1.5.4 to 1.5.20). The problem was in the repository package structure.

Problem: Under the same package were packages: repository, repositoryCustom and repositoryImpl.

Solution: Rearrange repository packages so that repository package contains repositoryCustom package and repositoryCustom package contains repositoryImpl:

repository 
   |
   ----- repositoryCustom
             |
             ----- repositoryImpl
ognjenkl
  • 1,407
  • 15
  • 11
2

Using Spring Boot I had this error thrown at me for a full day before I realised the significance the method name carried.

Kudos to @avi.elkharrat, who answered above, for leading me down the path to finding my solution.

Here's my scenario and how I fixed it.

I was working on an api that enabled users to make an api call to find customers by first name.

The classes that matter in this fix are the domain class and the repository that I will show below respectively.

public class Customer {

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

private String firstname;
private String lastname;

}

public interface CustomerRepository extends JpaRepository <Customer, Long> {

Customer findByFirstName(String firstname);

}

When the application was started above code the error following was thrown,

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract guru.springfamework.domain.Customer guru.springfamework.repositories.CustomerRepository.findByFirstName(java.lang.String)! No property firstName found for type Customer! Did you mean 'firstname'?

I searched my codebase for the camel case version of my reference field, firstName, mentioned in the error message. It wasn't there.

However, I realised that that value was being generated by Spring Data from the name of the custom method I created in the repository.

findByFirstName() in the repository was looking for firstName.

When I changed the method name to findByfirstname(), which matched the Customer domain class field private String firstname; all worked fine, the property was found.

Treat findBy as generic method, if you want to customise it, it needs to match the field that you are trying to find. findBy and then attached the name of your field property

Hope this helps someone out.

codeskin
  • 147
  • 1
  • 1
  • 8
2

Often this issue happens for typo issues, in my case, the problem was not about Repository or Service layers, my problem was about the Controller layer!!!

below is my controller snippets code and as you can see for the sortColumn variable i had added "nconst" instead "tconst" the correct field name in my related entity was "tconst" and the Spring was not able to figure out what is this field, i should have entered "tconst"

@GetMapping("/getAll")
    public ResponseEntity<Page> getAll(@RequestParam(defaultValue = "0") int page,
                                       @RequestParam(defaultValue = "10") int size,
                                       @RequestParam(defaultValue = "nconst") String sortColumn,
                                       @RequestParam(defaultValue = "asc") String sortOrder)
    { 
....
}
mi_mo
  • 135
  • 1
  • 8
1

Please Check property name in the defualt call of repo e.i repository.findByUsername(username)

Shahid Hussain Abbasi
  • 2,508
  • 16
  • 10
1

this might help someone who had similar issue like me , i followed all naming and interface standards., But i was still facing issue.

My param name was -->  update_datetime 

I wanted to fetch my entities based on the update_datetime in the descending order, and i was getting the error

org.springframework.data.mapping.PropertyReferenceException: No property update found for type Release!

Somehow it was not reading the Underscore character --> ( _ )

so for workaround i changed the property name as  --> updateDatetime 

and then used the same for using JpaRepository methods.

It Worked !

Ashish Shetkar
  • 1,414
  • 2
  • 18
  • 35
1

I experienced a similar issue and got the same error. I had this as my code.

List<Users> list = userRepo.findAll(Sort.by(Direction.ASC, "userId", "memberLevel");

I got the the following error:

org.springframework.data.mapping.PropertyReferenceException: No property userId found for type User!

Since userId is inside a primary key object as follows:

private UserPk pk;

The userId is inside UserPk:

@EmbeddedId
@AttributeOverrides({
        @AttributeOverride(name = "userId", column = @Column(name = "USER_ID", nullable = false, length = 10)),
        @AttributeOverride(name = "currency", column = @Column(name = "CAT_CODE", nullable = false, length = 4)),
        @AttributeOverride(name = "memberLevel", column = @Column(name = "MEMBER_LEVEL", nullable = false, length = 4))})
public UserPk getPk() {
    return pk;
}

The solution was the change it so that it references the primary key property name

List<Users> list = userRepo.findAll(Sort.by(Direction.ASC, "pk.userId", "pk.memberLevel");
ron
  • 239
  • 3
  • 18
0

In JPA a relationship has a single owner, and by using mappedByin 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.

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.

V G
  • 18,822
  • 6
  • 51
  • 89
0

If your project used Spring-Boot ,you can try to add this annotations at your Application.java.

@EnableJpaRepositories(repositoryFactoryBeanClass=CustomRepositoryFactoryBean.class)
@SpringBootApplication

public class Application {.....
0

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();
}
marvin ma
  • 21
  • 2
0

You should have that property defined in your model or entity class.

Dila Gurung
  • 1,726
  • 21
  • 26
0

In Addition to the suggestions, I would also suggest annotating your Repository interface with @Repository.

The Spring IOC may not detect this as a repository and thus be unable to detect the entity and its corresponding property.

Akshay
  • 457
  • 5
  • 14
  • Not true. @ Repository can be omitted when an interface extends JpaRepository because Spring Data JPA will create CategoryRepositoryImpl implementation class automatically. One more note. JpaRepository itself is annotated with @ NoRepositoryBean. What it means is Spring Data JPA won't created JpaRepositoryImpl bean for you. – codeskin Aug 25 '22 at 12:23
0

If you are using a composite key in your bean, your parameter will be an object. You need to adjust your findBy method according to the new combination.

@Embeddable
public class CombinationId implements Serializable {

  private String xId;
  private String yId;
}

public class RealObject implements Serializable, Persistable<CombinationId> {

  @EmbeddedId private CombinationId id;
}

In that case, your repository findBy method should be as this

@Repository
public interface PaymentProfileRepository extends JpaRepository<RealObject, String> {

  List<RealObject> findById_XId(String someString);
}
kuyu
  • 352
  • 3
  • 11
0

If you are using ENUM like MessageStatus, you may need a converter. Just add this class:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Convert ENUM type in JPA.
 */
@Converter(autoApply = true)
public class MessageStatusConverter implements AttributeConverter<MessageStatus, Integer> {
  @Override
  public Integer convertToDatabaseColumn(MessageStatus messageStatus) {
    return messageStatus.getValue();
  }

  @Override
  public MessageStatus convertToEntityAttribute(Integer i) {
    return MessageStatus.valueOf(i);
  }
}
Zon
  • 18,610
  • 7
  • 91
  • 99
0

I use projections and had the same error.

I had used getIssueTime(); instead of getCreateTime();

When I fixed the property named and the problem was solved.

menoktaokan
  • 346
  • 3
  • 13
0

This kind of issue is due to missing constructors in the class. Create default constructors

shashigura
  • 133
  • 1
  • 2
  • 8
0

You can implement from PagingAndSortingRepository.

Mafei
  • 3,063
  • 2
  • 15
  • 37
0

In my case my attribute name was "card_set_code", I just changed to "cardSetCode" and worked

0

My issue resolved after i changed the property name from comp_id to compId in the model file and then changed the delete method to deleteByCompId. It worked

0

I used post_id and ran into this exception.

But when I replaced all the post_id with postId. It's working fine. For more details:

https://github.com/Manohar-1/BlogApplication/issues/7

Manohar
  • 11
  • 3
  • While links to external websites are allowed, it's appreciated if your answer contains all relevant information in the answer itself, with external links used as a reference. This is because links can break over time or the content can change. - [from review](https://stackoverflow.com/review/late-answers/34852473) – Miss Skooter Aug 18 '23 at 13:24