24

我有两个实体,一个用户和一个注册用户。

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

因此,这是具有关联用户字段的注册用户实体:

@Entity
public class RegisteredUser implements Serializable {

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

这是一个用户名:

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

2 回答 2

29

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

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

如果未找到整个字段名称,还有一些代码将大写字符视为字段分隔符。因此,如果您在第二个变量中没有userUsername字段是RegisteredUser

public interface RegisteredUserRepository extends CrudRepository<RegisteredUser,String> {
    List<RegisteredUser> findRegisteredUserByUserUsername(String username);
}
于 2016-05-12T21:16:11.920 回答
0

You may also simply use a library like this one, which lets you build dynamic filters (supports logical operators, comparators, enums, dates, booleans, joins, functions, and much more): https://github.com/turkraft/spring-filter

You won't have to create any repository interface and you will be able to use the provided query builder in your client app directly.

Example query:

/search?filter= average(ratings) > 4.5 and brand.name in ('audi', 'land rover') and (year > 2018 or km < 50000) and color : 'white' and accidents is empty

Usage:

@GetMapping(value = "/search")
public List<Entity> search(@EntityFilter Specification<Entity> spec, Pageable page) {
  return repo.findAll(spec, page);
}

Don't forget the dependency:

<dependency>
    <groupId>com.turkraft</groupId>
    <artifactId>spring-filter</artifactId>
    <version>0.9.5</version>
</dependency>

You may also check rsql, although it's a bit outdated now https://github.com/jirutka/rsql-parser

于 2021-04-13T09:07:48.370 回答