我引用了这个 springboot 教程,我在我的项目中使用了 spring data,我试图添加 data to database 。当我尝试使用以下 . bt 时,我收到一条错误消息



这是我的代码,

//my controller

@RequestMapping("/mode")
    public String showProducts(ModeRepository repository){
        Mode m = new Mode();
        m.setSeats(2);
        repository.save(m); //this is where the error getting from
        return "product";
    }


//implementing crud with mode repository
@Repository
public interface ModeRepository extends CrudRepository<Mode, Long> {

}

 //my mode class
@Entity
@Table(name="mode")
public class Mode implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false)
    private int idMode;


    @Column(nullable=false)
    private int seats;

    //assume that there are getters and setters
}

我是 springboot 的新手,有人能告诉我我做错了什么吗?
如果有人能给我提供一个链接来了解 springdata,我将不胜感激
除了 spring documentation

最佳答案

更改您的 Controller 代码,使 ModeRepository 成为私有(private)的 Autowiring 字段。

    @Autowired //don't forget the setter
    private ModeRepository repository;

    @RequestMapping("/mode")
    public String showProducts(){
        Mode m = new Mode();
        m.setSeats(2);
        repository.save(m); //this is where the error getting from
        return "product";
    }

10-06 00:57