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> {
}
# 1 楼答案
我有类似的东西。这是因为您使用的是更新的版本
您可以通过以下方式进行修复:
# 2 楼答案
如果只想按id搜索,请使用findById或getOne而不是findOne
函数
findOne()
接收一个Example<S>
,此方法用于通过示例查找,因此需要提供示例对象和要检查的字段您可以通过示例找到如何使用“查找”
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.matchers
但基本上是这样的
# 3 楼答案
JpaRepository中的findOne方法定义为:
Reference
和yo正在传递一个字符串作为参数。 如果要按用户查找。电子邮件方法必须定义为:
这种麦加主义在query creation document中有解释