问题

调用repository.save(user);,其中repositoryUserRepository的实例,而user.toStringUser[id=0, userName='asd', password='asd'],我的控制器给出以下错误:

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 repository不应用作参数:
...

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


...

您可以像这样使用@Autowired吗?

@Autowired
 private UserRepository repository;


然后重试?!

希望对您有所帮助。

10-07 11:58