gpt4 book ai didi

java - 为什么我不能在 Spring Boot 中使用它的 UserRepository 保存我的 @Entity User

转载 作者:行者123 更新时间:2023-12-02 03:27:21 25 4
gpt4 key购买 nike

问题

调用repository.save(user);,其中repositoryUserRepositoryuser.toString的实例是 User[id=0, userName='asd', password='asd'],我的 Controller 给出以下错误:

nested exception is java.lang.IllegalArgumentException: Invoked method public abstract java.lang.Object org.springframework.data.repository.CrudRepository.save(java.lang.Object) is no accessor method!] with root cause

java.lang.IllegalArgumentException: Invoked method public abstract java.lang.Object org.springframework.data.repository.CrudRepository.save(java.lang.Object) is no accessor method!

详细信息

我知道 repository.save(new User("user1", "pass1")); 有效,因为我使用以下方法测试了我的存储库:

public CommandLineRunner demo(UserRepository repository) {
return (args) -> {
// save a couple of users
repository.save(new User("user1", "pass1"));
repository.save(new User("user2", "pass2"));
}
}

这是页面的完整请求映射:

RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
User user = new User();
model.addAttribute("user", user);
return "registrations/register";
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUserAccount(WebRequest request,
@ModelAttribute("user") @Valid User user,
BindingResult result,
UserRepository repository) {
if (!result.hasErrors()) {

System.out.println(user);
repository.save(user);
}
return "redirect:/";

}

这是 UserRepository:

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {

List<User> findByUserName(String UserName);
}

这是用户@Entity:

@Entity
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String userName;
private String password;

protected User() {}

public User(String userName, String password) {
this.userName = userName;
this.password = password;
}

// standard getters and setters

@Override
public String toString() {
return String.format(
"User[id=%d, userName='%s', password='%s']",
id, userName, password);
}

}

最佳答案

Controller 代码中的UserRepository存储库似乎不应该用作参数:...

public String registerUserAccount(WebRequest request,
@ModelAttribute("user") @Valid User user,
BindingResult result,
UserRepository repository)

...

你可以像这样使用@Autowired吗:

@Autowired 
private UserRepository repository;

然后再试一次?!

希望这有帮助。

关于java - 为什么我不能在 Spring Boot 中使用它的 UserRepository 保存我的 @Entity User,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38628434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com