【发布时间】:2016-12-30 08:29:31
【问题描述】:
spring-data-jpa 实现存储库
我刚开始使用 Spring-boot 和 Accessing-data-jpa,我决定看看 https://spring.io 提供的指南之一。我决定看的指南是accessing-data-jpa。我跟随它到最后,然后运行我的应用程序。令我惊讶的是,我收到了一条错误消息。
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type User!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
所以问题出在哪里似乎很容易。它在我的用户类中寻找属性“名称”。但我实际上并没有在任何地方使用属性“名称”。
我的仓库界面:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String userName);
}
我的用户类:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userID;
private LocalDateTime joinDate;
private String userName;
private String email;
protected User(){}
public User(String userName){
this.userName = userName;
}
@Override
public String toString() {
return String.format("User[id=%d, userName=%s, email= %s]",userID, userName,email);
}
}
应用类:
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner demo(UserRepository repository){
return (args) -> {
//Save a few Users
repository.save(new User("Niek"));
repository.save(new User("Costas"));
repository.save(new User("Eric"));
repository.save(new User("Philip"));
repository.save(new User("Barry"));
//Fetch all Users
log.info("Users Found With findAll()");
log.info("--------------------------");
for(User user: repository.findAll()){
log.info(user.toString());
}
log.info("");
//Fetch one User
log.info("User found With findOne(1L)");
log.info("--------------------------");
log.info(repository.findOne(1L).toString());
//Fetch one User By Name
log.info("User found with findByName(\"Niek\")");
log.info("--------------------------");
for(User user: repository.findByName("Niek")){
log.info(user.toString());
}
};
}
}
我假设你们中的一些人认为你没有实现你的存储库。
在典型的 Java 应用程序中,您希望编写一个实现 CustomerRepository 的类。但这就是 Spring Data JPA 如此强大的原因:您不必编写存储库接口的实现。当您运行应用程序时,Spring Data JPA 会即时创建一个实现。
这让我想到了我的问题:
- 是因为 Spring Data JPA 动态提供的存储库实现,它要求一个属性“名称”而不是只使用我提供的属性“用户名”吗?
- 如果对上一个问题的回答是“是”,是否可以假设提供您自己的实现将更不容易出错?因为生成的实现似乎符合某种约定。
【问题讨论】:
标签: spring spring-boot spring-data spring-data-jpa