java Spring数据存储库按字段字段查找的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37193901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:16:56  来源:igfitidea点击:

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

javaspringhibernatespring-repositories

提问by nbro

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.

注册用户有一个类型为 user 的字段。我想在与此注册用户实体相关的 spring 数据存储库中有一个方法,通过连接到注册用户的用户的用户名搜索所有注册用户。

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;
    ...
}

回答by Ilya

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

Spring Data(至少 1.12.x 版本)使用PropertyPath#from方法为从方法名称构造的谓词提取属性的路径。根据消息来源,它使用下划线作为“字段分隔符”。所以第一个变体如下

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 userUsernamefield in RegisteredUsersecond varian is

如果未找到整个字段名称,也有将大写字符视为字段分隔符的代码。所以如果你userUsernameRegisteredUser第二个变量中没有一个字段是

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