有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我不能在代码中使用findOne()方法

我的应用程序中有错误,因为我使用findOne()方法。下面是我的简单代码。在用户类中,我的id是字符串电子邮件,这是我在类UserService中尝试使用的id,如下所示:

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

但我有一个错误:

method findOne in interface org.springframework.data.repository.query.QueryByExampleExecutor cannot be applied to given types;
required: org.springframework.data.domain.Example
found: java.lang.String
reason: cannot infer type-variable(s) S (argument mismatch; java.lang.String cannot be converted to 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> {
}

共 (3) 个答案

  1. # 1 楼答案

    我有类似的东西。这是因为您使用的是更新的版本

    您可以通过以下方式进行修复:

    return userRepository.findById(email).orElse(null);
    
  2. # 2 楼答案

    如果只想按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); 
    
  3. # 3 楼答案

    JpaRepository中的findOne方法定义为:

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

    Reference

    和yo正在传递一个字符串作为参数。 如果要按用户查找。电子邮件方法必须定义为:

    User findOneByEmail (String email);
    

    这种麦加主义在query creation document中有解释