Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use unit of work in rest controller properly?

public interface CourseRepo extends CrudRepository<Course, Long> {

}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor 
 public class UnitOfWork {

    CourseRepo courses;
    StudentRepository students;
    StudyProgramRepository studyPrograms;
    StudySchemeRepo studySchemes;
    FeeStructureRepository feeStructures;
}
@RestController
public class TestController {
    
    @Autowired
    UnitOfWork uow;
    

    @GetMapping("/addcr")
    public String addCourse() {
        
        Course cr = new Course();
        cr.setTitle("DingDong course");
        uow.getCourses().save(cr);

        return "course Added..!!" ;
    }
APPLICATION FAILED TO START
***************************

Description:

Field uow in com.srs.TestController required a bean of type 'com.srs.uow.UnitOfWork' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.srs.uow.UnitOfWork' in your configuration.

if i remove autowired and add a bean

@RestController
public class TestController {
    
    @Bean
    public UnitOfWork uow() {
        return new UnitOfWork();
    }

    @GetMapping("/addcr")
    public String addCourse() {
        
        Course cr = new Course();
        cr.setTitle("DingDong course");
        uow().getCourses().save(cr);

        return "course Added..!!" ;
    }

java.lang.NullPointerException: Cannot invoke "com.srs.jpa.CourseRepo.save(Object)"
because the return value of "com.srs.uow.UnitOfWork.getCourses()" is null

i tried both autowired and in this case how can i use autowired or bean properly ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your class need to be annotated with @Component to be used with DI provider by @Autowired annotation

For the same reason each repository of your class need to be annotated with @Autowired

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading