我不能在我的代码中使用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);
在查询创建文档中解释了这种机制
- java.lang.NoClassDefFoundError:org / hibernate / cfg / Configuration
- 使用cascade =“save-update”保存时出现Hibernateexception
- CollectionOfElements上的java.util.ConcurrentModificationException
- hibernate中的createSQLQuery使用Prepared Statement?
- 在Hibernate和PostgreSQL中使用UserType的数组 – > MappingException
- 如何取消正在运行的SQL查询?
- 使用JBoss和Spring在Java Web应用程序之间共享业务对象实例的最佳方法是什么?
- 如何将@UniqueConstraint与单表inheritance(JPA)一起使用?
- Sprint引导数据JPA:没有类型为’java.util.Set ‘的限定bean