简体   繁体   中英

How do you create a Spring JPA repository findBy query using a property that contains a keyword?

Here is a simplified example of my problem. I have this repository and entity class.

public interface ThingRepository extends JpaRepository<ThingEntity, Long> {
    ThingEntity findByFooInAndBar(String fooIn, String bar);
}

@Entity
public class ThingEntity {
    @Column(name="FOO_IN", nullable=false, length=1)
    private String fooIn;

    public String getFooIn() {
        return fooIn;
    }

    public setFooIn(String fooIn) {
        this.fooIn = fooIn;
    }

    /* not including bar property for brevity's sake */
}

Spring is throwing the following exception.

org.springframework.data.mapping.PropertyReferenceException: No property foo found for type ThingEntity!

It looks like Spring is taking the method findByFooInAndBar and thinks that foo is my property name and in is a keyword for matching values within a collection.

How do I get it to understand that the property name is fooIn , not foo ?

To overcome this problem, I've defined the query manually using the @Query annotation. I'll happily accept anyone else's answer if they find a solution that doesn't require a manual query.

public interface ThingRepository extends JpaRepository<ThingEntity, Long> {

    @Query("SELECT t FROM Thing t WHERE t.fooIn = ?1 AND t.bar = ?2")
    ThingEntity findByFooInAndBar(String fooIn, String bar);
}

Spring is parsing 'In' in your method to create the query. Check the link for create your query: you should change the name of the variable fooIn to fooin or something like that...

I observed the code kindly and notice your return is not a list but an object .
Change that part to List<ThingEntity> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM