Spring data repository's method to find by the field of a field

那年仲夏 提交于 2019-12-03 09:16:48

问题


I've two entities, a user and a registered user.

A registered user has a field of type user. I would like to have a method in the spring data repository related to this registered user entity to search all registered users by the username of the user that is connected to the registered user.

So, this is the registered user entity with an associated user field:

@Entity
public class RegisteredUser implements Serializable {

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

and this is a user with a username:

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

回答1:


Spring Data (at least 1.12.x version) uses PropertyPath#from method to extract path to a property for a predicate constructed from method name. According to sources it uses underscore as "field separator". So first variant is as follows

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

There is also code which treat an uppercase char as field separator if whole field name is not found. So if you don't have a userUsername field in RegisteredUser second varian is

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


来源:https://stackoverflow.com/questions/37193901/spring-data-repositorys-method-to-find-by-the-field-of-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!