delucasvb
delucasvb

Reputation: 5753

Spring Data JPA query generation by field

I had a method in a ProjectRepository that looked something like this:

findByUserID(int userID);

This would list all projects that reference a certain user. Because of other requirements, I now need to reference the User from the Project, instead of just the userID, like so:

@ManyToOne
@JoinColumn(name = "userID", referencedColumnName = "userID")
private User user;

Which used to just be:

int userID;

So I replaced the method with:

findByUser(User user);

But this requires an extra call to the database to get the User object for a given userID. Is there a way to use the first method with my new class? If I just keep the first method, I get a

org.springframework.data.mapping.PropertyReferenceException: No property ID found for type User! Traversed path: Project.user.

Is this possible without writing a custom query?

Upvotes: 4

Views: 751

Answers (2)

james_s_tayler
james_s_tayler

Reputation: 1933

Assuming the User class contains is defined as:

public class User {
    private int userId;

    public User(int userId) {
        this.userId = userId;
    }
    //getters setters ommitted
}

and the Project class has a User object in it like so:

public class Project {
    private User user;

    public Project() {
    }
    //rest ommitted
}

It should according to the documentation be able to write a custom query in the repository that access the nested properties like project.user.userId by writing

findByUserUserId(int userId);

Or at least that's what I understood from reading the docs here

Upvotes: 3

james_s_tayler
james_s_tayler

Reputation: 1933

Try using the @PrimaryKeyJoinColumn annotation.

Upvotes: 0

Related Questions