org.springframework.beans.factory.UnsatisfiedDependencyException:添加新存储库后发生错误

问题描述

您好,我试图在一个项目上工作时,当我在单个模型上工作时,一切都非常顺利,如您在“学生”下面看到的那样

StudentController

package net.springboot.javaguides.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import net.springboot.javaguides.entity.Student;
import net.springboot.javaguides.repository.StudentRepository;

@Controller
@RequestMapping("/students/")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;    
    
    @GetMapping("showForm")
    public String showStudentForm(Student student) {
        return "student/add-student";
    }
    
    @GetMapping("list")
    public String students(Model model) {
        model.addAttribute("students",this.studentRepository.findAll());
        return "student/index";
    }
    
    @PostMapping("add")
    public String addStudent(@Valid Student student,BindingResult result,Model model) {
        if(result.hasErrors()) {
            return "student/add-student";
        }
        
        this.studentRepository.save(student);
        return "redirect:list";
    }
    
    
    @GetMapping("edit/{id}")
    public String showUpdateForm(@PathVariable ("id") long id,Model model) {
        Student student = this.studentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
        
        model.addAttribute("student",student);
        return "student/update-student";
    }
    
    @PostMapping("update/{id}")
    public String updateStudent(@PathVariable("id") long id,@Valid Student student,Model model) {
        if(result.hasErrors()) {
            student.setId(id);
            return "student/update-student";
        }
        
        // update student
        studentRepository.save(student);
        
        // get all students ( with update)
        model.addAttribute("students",this.studentRepository.findAll());
        return "student/index";
    }
    
    @GetMapping("delete/{id}")
    public String deleteStudent(@PathVariable ("id") long id,Model model) {
        
        Student student = this.studentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
        
        this.studentRepository.delete(student);
        model.addAttribute("students",this.studentRepository.findAll());
        return "student/index";
        
    }
}

StudentEntity

package net.springboot.javaguides.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "students")
public class Student {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @Column(name = "name")
    private String name;
    
    @Column(name = "email")
    private String email;
    
    @Column(name = "phone_no")
    private long phoneNo;
    
    
    public Student() {
        super();
    }

    public Student(String name,String email) {
        super();
        this.name = name;
        this.email = email;
    }
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public long getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(long phoneNo) {
        this.phoneNo = phoneNo;
    }
}

StudentRepository

package net.springboot.javaguides.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import net.springboot.javaguides.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student,Long>{
    List<Student> findByName(String name);
}

现在我正尝试添加一些新模型,如下所示,但是我有错误

CourseController

package net.springboot.javaguides.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import net.springboot.javaguides.entity.Course;
import net.springboot.javaguides.repository.CourseRepository;

@Controller
@RequestMapping("/courses/")
public class CourseController {

    @Autowired
    private CourseRepository courseRepository;  
    
    @GetMapping("showForm")
    public String showCourseForm(Course course) {
        return "add-course";
    }
    
    @GetMapping("list")
    public String courses(Model model) {
        model.addAttribute("courses",this.courseRepository.findAll());
        return "index";
    }
    
    @PostMapping("add")
    public String addCourse(@Valid Course course,Model model) {
        if(result.hasErrors()) {
            return "add-course";
        }
        
        this.courseRepository.save(course);
        return "redirect:list";
    }
    
    
    @GetMapping("edit/{id}")
    public String showUpdateForm(@PathVariable ("id") long id,Model model) {
        Course course = this.courseRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
        
        model.addAttribute("course",course);
        return "update-course";
    }
    
    @PostMapping("update/{id}")
    public String updateCourse(@PathVariable("id") long id,@Valid Course course,Model model) {
        if(result.hasErrors()) {
            course.setId(id);
            return "update-course";
        }
        
        // update course
        courseRepository.save(course);
        
        // get all courses ( with update)
        model.addAttribute("courses",this.courseRepository.findAll());
        return "index";
    }
    
    @GetMapping("delete/{id}")
    public String deleteCourse(@PathVariable ("id") long id,Model model) {
        
        Course course = this.courseRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
        
        this.courseRepository.delete(course);
        model.addAttribute("courses",this.courseRepository.findAll());
        return "index";
        
    }
}

课程实体

package net.springboot.javaguides.entity;


import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Courses")
public class Course {
    
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
    
        @Column(name = "cours_name")
     private String cours_name;
     
        @Column(name = "date_debut")
     private Date date_debut;
     
        @Column(name = "date_fin")
     private Date date_fin;
     
        @Column(name = "enseignant")
     private String enseignant;
     
        @Column(name = "type_cours")
     private String type_cours;
     
        @Column(name = "filliere")
     private String filliere;
    
     public Course() {
         super();
     }
     
     public Course(String cours_name,Date date_debut,Date date_fin,String enseignant,String type_cours,String filliere) {
        super();
        this.cours_name = cours_name;
        this.date_debut = date_debut;
        this.date_fin = date_fin;
        this.enseignant = enseignant;
        this.type_cours = type_cours;
        this.filliere = filliere;
    }
        
     
     public Long getId() {
        return id;
    }
    public String getCours_name() {
        return cours_name;
    }

    public void setCours_name(String cours_name) {
        this.cours_name = cours_name;
    }

    public Date getDate_debut() {
        return date_debut;
    }

    public void setDate_debut(Date date_debut) {
        this.date_debut = date_debut;
    }

    public Date getDate_fin() {
        return date_fin;
    }

    public void setDate_fin(Date date_fin) {
        this.date_fin = date_fin;
    }

    public String getEnseignant() {
        return enseignant;
    }

    public void setEnseignant(String enseignant) {
        this.enseignant = enseignant;
    }

    public String getType_cours() {
        return type_cours;
    }

    public void setType_cours(String type_cours) {
        this.type_cours = type_cours;
    }

    public String getfilliere() {
        return filliere;
    }

    public void setfilliere(String filliere) {
        this.filliere = filliere;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
    
     
}

**

CourseRepository

**

package net.springboot.javaguides.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import net.springboot.javaguides.entity.Course;

@Repository
public interface CourseRepository extends JpaRepository<Course,Long>{
    List<Course> findByName(String cours_name);
}

我有错误


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__,| / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2020-08-27 13:44:03.876  INFO 9188 --- [  restartedMain] s.j.SpringbootthymeleafWebAppApplication : Starting SpringbootthymeleafWebAppApplication on DESKTOP-5D7IMCJ with PID 9188 (C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master\target\classes started by yassi in C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master)
2020-08-27 13:44:03.880  INFO 9188 --- [  restartedMain] s.j.SpringbootthymeleafWebAppApplication : No active profile set,falling back to default profiles: default
2020-08-27 13:44:03.941  INFO 9188 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-08-27 13:44:03.941  INFO 9188 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-08-27 13:44:04.881  INFO 9188 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-08-27 13:44:04.957  INFO 9188 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 68ms. Found 2 repository interfaces.
2020-08-27 13:44:05.415  INFO 9188 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringcglib$$97fbb782] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-08-27 13:44:05.849  INFO 9188 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-08-27 13:44:05.868  INFO 9188 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-27 13:44:05.868  INFO 9188 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.12
2020-08-27 13:44:05.876  INFO 9188 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_221\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_221/bin/server;C:/Program Files/Java/jre1.8.0_221/bin;C:/Program Files/Java/jre1.8.0_221/lib/amd64;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft sql Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft sql Server\120\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft sql Server\120\Tools\Binn\;C:\Program Files\Microsoft sql Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft sql Server\120\DTS\Binn\;C:\Program Files\Microsoft sql Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft sql Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft sql Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft sql Server\110\DTS\Binn\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\MysqL\MysqL Server 5.1\bin;C:\Users\yassi\AppData\Local\Microsoft\WindowsApps;;C:\Users\yassi\AppData\Local\Programs\Microsoft VS Code\bin;D:\eclipse;;.]
2020-08-27 13:44:05.990  INFO 9188 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-27 13:44:05.990  INFO 9188 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2049 ms
2020-08-27 13:44:06.025  INFO 9188 --- [  restartedMain] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2020-08-27 13:44:06.031  INFO 9188 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2020-08-27 13:44:06.031  INFO 9188 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2020-08-27 13:44:06.031  INFO 9188 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
2020-08-27 13:44:06.031  INFO 9188 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2020-08-27 13:44:06.203  INFO 9188 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-08-27 13:44:06.332  INFO 9188 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-08-27 13:44:06.388  INFO 9188 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2020-08-27 13:44:06.630  INFO 9188 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2020-08-27 13:44:06.632  INFO 9188 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-08-27 13:44:06.776  INFO 9188 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-08-27 13:44:06.917  INFO 9188 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MysqL5InnoDBDialect
2020-08-27 13:44:07.829  INFO 9188 --- [  restartedMain] j.LocalContainerEntityManagerfactorybean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-27 13:44:07.871  INFO 9188 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-08-27 13:44:08.146  WARN 9188 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'courseController': Unsatisfied dependency expressed through field 'courseRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseRepository': Invocation of init method Failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List net.springboot.javaguides.repository.CourseRepository.findByName(java.lang.String)! No property name found for type Course!


解决方法

尝试在主类的顶部添加@EnableJpaRepositories(packages)

我遇到了同样的问题,我通过添加@EntityScan或@EnableJpaRepositories(packages)

进行了处理。 ,

日志已经说明了问题! .repository.CourseRepository.findByName(java.lang.String)!找不到课程类型的属性名称!您的Course实体没有名为name的属性,称为cours_name。将您的“课程”实体中的cours_name更改为在CourseRepository中的名称或更改方法的名称!