Nikola Ivkov
Nikola Ivkov

Reputation: 89

Spring JPA repository how to write a query

I have a User class, that is identified by id, and Skills class, that has its own id field, and also references User.

public class User {

    @Id
    @GeneratedValue
    private int id;

    @JsonIgnore
    @OneToOne(mappedBy = "user")
    private SoftSkills softSkills;
}

the other one has

    @Entity
 public class SoftSkills {

    @Id
    @GeneratedValue
    private int id;

    @OneToOne
    @JoinColumn
    private User user;
}

Is there a simple way to write a query, implementing the JPARepository, that would search the SoftSkills class by using user.id field as a parameter and return a SoftSkills object as a result?

Upvotes: 1

Views: 511

Answers (1)

Niels Masdorp
Niels Masdorp

Reputation: 2428

You can, from the documentation:

Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example. At query creation time you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties. Assume a Person has an Address with a ZipCode. In that case a method name of

List<Person> findByAddressZipCode(ZipCode zipCode);

creates the property traversal x.address.zipCode. The resolution algorithm starts with interpreting the entire part (AddressZipCode) as the property and checks the domain class for a property with that name (uncapitalized). If the algorithm succeeds it uses that property. If not, the algorithm splits up the source at the camel case parts from the right side into a head and a tail and tries to find the corresponding property, in our example, AddressZip and Code. If the algorithm finds a property with that head it takes the tail and continue building the tree down from there, splitting the tail up in the way just described. If the first split does not match, the algorithm move the split point to the left (Address, ZipCode) and continues.

So this will do the trick:

SoftSkills findByUserId(int id);

Reference; Spring Data JPA Documentation

Upvotes: 3

Related Questions