簡體   English   中英

我無法在我的代碼中使用 findOne() 方法

[英]I can't use findOne() method in my code

我的應用程序有錯誤,因為我使用了 findOne() 方法。 在我的簡單代碼下面。 在 User 類中,我的 id 是 String email ,這是我試圖在我的 UserService 類中使用的 id,如下所示:

public User findUser(String email){
    return userRepository.findOne(email);
}

但我有這個錯誤:

接口 org.springframework.data.repository.query.QueryByExampleExecutor 中的方法 findOne 不能應用於給定類型;
要求:org.springframework.data.domain.Example
找到:java.lang.String
原因:無法推斷類型變量 S(參數不匹配;java.lang.String 無法轉換為 org.springframework.data.domain.Example)

用戶類:

@Entity
@Data
@Table(name = "User")
public class User {
    @Id
    @Email
    @NotEmpty
    @Column(unique = true)
    private String email;

    @NotEmpty
    private String name;

    @NotEmpty
    @Size(min = 5)
    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Task> tasks;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "USER_ROLE", joinColumns = {
        @JoinColumn(name = "USER_EMAIL", referencedColumnName = "email")
    }, inverseJoinColumns = {@JoinColumn(name = "ROLE_NAME", referencedColumnName = "name")})
    private List<Role> roles;
}

和用戶存儲庫:

public interface UserRepository extends JpaRepository<User, String> {
}

當您只想按 ID 搜索時,請使用findByIdgetOne而不是findOne

public User findUser(String email){
    return userRepository.getOne(email); // throws when not found or
                                         // eventually when accessing one of its properties
                                         // depending on the JPA implementation
}

public User findUser(String email){
    Optional<User> optUser = userRepository.findById(email); // returns java8 optional
    if (optUser.isPresent()) {
        return optUser.get();
    } else {
        // handle not found, return null or throw
    }
}

函數findOne()接收一個Example<S> ,該方法用於通過示例查找,因此您需要提供示例對象和要檢查的字段。

您可以找到如何使用示例查找。

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.matchers

但它基本上是這樣的。

User user = new User();                          
person.setName("Dave");                           

ExampleMatcher matcher = ExampleMatcher.matching()     
    .withIgnorePaths("name")                         
    .withIncludeNullValues()                             
    .withStringMatcherEnding();

Example<User> example = Example.of(user, matcher); 

我有類似的東西。 這是因為您使用的是較新的版本。

您可以通過以下方式修復它:

return userRepository.findById(email).orElse(null);

JpaRepository 中的 findOne 方法定義為:

<S extends T> Optional<S> findOne(Example<S> example)

參考

你正在傳遞一個字符串作為參數。 如果要通過 User.email 查找,則必須將方法定義為:

User findOneByEmail (String email);

這種機制在查詢創建文檔中有解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM