Java – field lookup method of spring data repository

I have two entities, one user and one registered user

The registered user has a field of type user I think there is a method in the data repository of spring registered user entity to search all registered users by the user name of the user connected to the registered user

Therefore, this is a registered user entity with an associated user field:

@Entity
public class RegisteredUser implements Serializable {

    ... 
    @OneToOne
    @JoinColumn(name = "USERNAME_FK")
    private User user;
    ...
}

This is a user name:

@Entity
public class User implements Serializable { 
    ...
    @Id
    @Column(nullable = false)
    protected String username;
    ...
}

Solution

Spring data (at least version 1.12. X) uses the propertypath#from method to extract the path of the property for the predicate constructed from the method name According to sources, it uses underscores as field separators So the first variant is as follows

public interface RegisteredUserRepository extends CrudRepository<RegisteredUser,String> {
    List<RegisteredUser> findRegisteredUserByUser_Username(String username);
}

If the entire field name cannot be found, some codes treat uppercase characters as field separators Therefore, if you do not have the userusername field in registereduser, the second variant is

public interface RegisteredUserRepository extends CrudRepository<RegisteredUser,String> {
    List<RegisteredUser> findRegisteredUserByUserUsername(String username);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>