我不能在我的代码中使用findOne()方法
我的应用程序中有错误,因为我使用了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 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 roles; }
和UserRepository:
public interface UserRepository extends JpaRepository { }
如果只想按id搜索,请使用findById或getOne而不是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 optUser = userRepository.findById(email); // returns java8 optional if (optUser.isPresent()) { return optUser.get(); } else { // handle not found, return null or throw } }
函数findOne()
接收一个Example
,此方法用于通过示例查找,因此您需要提供示例对象和要检查的字段。
您可以通过示例找到如何使用find。
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 example = Example.of(user, matcher);
JpaRepository中的方法findOne定义为:
Optional findOne(Example example)
参考
和哟传递一个String作为参数。 如果要通过User.email查找,则必须将方法定义为:
User findOneByEmail (String email);
在查询创建文档中解释了这种机制
- Hibernate使用hibernate.jdbc.batch_versioned_data保存过时数据
- Hibernate向数据库发送多余的查询
- Hibernate:没有活动事务,createQuery无效
- 映射键值的Hibernate Criteria
- Hibernate比sql查询慢1000倍
- SpringMVC和Hibernate:CannotCreateTransactionException:无法打开Hibernate Session进行事务处理;
- 如果我在Hibernate中使用JPA,我的项目应该具有哪些依赖项?
- 在Microsoft sql server中连接/附加不同的表
- 给出java.lang.IllegalArgumentException的Hibernate查询:遍历的节点不能为null