Home > OS >  Spring REST shows a 404 error on POST request
Spring REST shows a 404 error on POST request

Time:02-24

I am getting error on REST POST requests

project hierarchy

I am using H2 db and this is how I configured it:

spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./db/daDb
spring.datasource.username=user
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update

Controller:

@RestController
@RequestMapping(path = "/student",consumes = "application/json")
public class StudentController
{
    private final studentDAO studentDAO;
    @Autowired
    public StudentController()
    {
        this.studentDAO = new studentDAO();
    }

    //todo Add student subject(student id,subject id) fixed with patch/put mapping
    //todo Add Exception Handling



    @PostMapping(path = "/")
    @ResponseStatus(HttpStatus.CREATED)
    public void postRequest(@NonNull @RequestBody student student)
    {
        student.setId(UUID.randomUUID());
        this.studentDAO.add(student);
    }
}

Service:

@Service
public class studentDAO extends daoTemplate<student,studentRepo>
{
    @Autowired
    private studentRepo studentRepo;

    @Override
    public void add(student temp)
    {
        this.studentRepo.save(temp);
    }

    @Override
    public void patchUpdate(student student,UUID id)
    {
        Optional<student> target = super.getRepo().findById(id);
        if(target.isPresent())
        {
            if(Objects.nonNull(student.getName()))
                target.get().setName(student.getName());
            if(Objects.nonNull(student.getSubjects()))
                target.get().setSubjects(student.getSubjects());
        }
    }

}

The DAO Template

@Service
public abstract class daoTemplate<entity,repo extends CrudRepository<entity,UUID>>
{
    private repo repo;

    public repo getRepo()
    {
        return repo;
    }

    public entity get(UUID id)
    {
        Optional<entity> temp = this.repo.findById(id);
        if(temp.isPresent())
        {
            return temp.get();
        }
        return null;
    }

    public Iterable<entity> getAll()
    {
        return this.repo.findAll();
    }

    public void update(entity temp)
    {
        if (Objects.nonNull(temp))
            this.repo.save(temp);
    }

    public void patchUpdate(entity temp,UUID id)
    {
        //Manually Written
    }

    public void delete(UUID id)
    {
        if(this.repo.existsById(id))
            this.repo.deleteById(id);
    }

    public void add(entity temp)
    {
        this.repo.save(temp);
    }

    public boolean check(UUID id)
    {
        return this.repo.existsById(id);
    }
}

Student Entity

@Entity
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class student
{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @NotBlank
    @NotEmpty
    private String name;

    @NonNull
    private int age;
    
    @ManyToMany(mappedBy = "students",cascade = {CascadeType.MERGE,CascadeType.DETACH,
    CascadeType.PERSIST,CascadeType.REFRESH},fetch = FetchType.EAGER)
    Collection<subject>subjects;

    public void addSubjectByID(Collection<UUID> subjectsIDs)
    {
        if(!subjectsIDs.isEmpty())
        {
            subjectDAO dao = new subjectDAO();
            subjectsIDs.stream().distinct()
                    .map((id) -> {
                        return dao.get(id);
                    })
                    .forEach((subject) -> {
                        this.subjects.add(subject);
                    });
        }
    }

}

The JSON request:

    {
    "name": "khalid kbashi",
    "age": 16,
    "subject": null
}

Response:

enter image description here

CodePudding user response:

i fixed it by : 1- Deleted the constructor from the controller 2- added field injection the studentDAO in the controller 3- removed @Service from daoTemplate 4- added an extra dash to the URI from "http://localhost:8080/student" to "http://localhost:8080/student/"

i think number 4 was the main issue

  • Related