Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API is always throwing 404 error in Spring boot maven multimodule project with H2 database

I am new to Spring boot and I have created a multi-module project(maven) with spring boot. And I created some REST APIs and connected to H2 database. The database is connected successfully and able to run in localhost.

This is my project tree.. User-Management is parent and core, serverAPI are child modules. And I have created packages for each module and added the relevant classes.

I have tried everything I know and searched google for like 5 days but nothing worked for me. I have included every code I wrote here. Please help me to find what the issue is. (I am using intellij idea 2020.3 ultimate)

enter image description here

User.java

package com.hms.usermanagement.core.model;
import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {

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

@Column(name = "full_name")
private String fullName;

@Column(name = "email")
private String email;

public User() {
}

public User(long id, String fullName, String email) {
    this.id = id;
    this.fullName = fullName;
    this.email = email;
}

public long getId() {
    return id;
}

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

public String getFullName() {
    return fullName;
}

public void setFullName(String fullName) {
    this.fullName = fullName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}}

UserRepository

package com.hms.usermanagement.core.repository;

import com.hms.usermanagement.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User,Long> {
 } 

Application

package com.hms.usermanagement.serverAPI.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.run(args);
}}

UserController

package con.hms.usermanagement.serverAPI.controller;


import com.hms.usermanagement.core.model.User;
import com.hms.usermanagement.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class UserController {

@Autowired
private UserRepository userRepository;

//Create Users
@PostMapping("/user")
public User createUser( @Validated @RequestBody User user){
    return userRepository.save(user);
}

//View all Users
@GetMapping("/users")
public List<User> getAllUsers(){
    return userRepository.findAll();
}

//Update Users
@PutMapping("/users/{id}")
public ResponseEntity <User> updateUser(@PathVariable(value = "id") long userId , @RequestBody User userDetails){
    Optional<User> user = userRepository.findById(userId);
    if(user.isPresent()){
        User _user = user.get();
        _user.setFullName(userDetails.getFullName());
        _user.setEmail(userDetails.getEmail());
        return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
    }else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

//Delete Users
@DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(@PathVariable(value = "id") long userId){
    userRepository.findById(userId);
    userRepository.deleteById(userId);
    return ResponseEntity.ok().build();
}

application.properties

spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

#enable H2 console
spring.h2.console.enabled=true

#custom H2 console
spring.h2.console.path=/h2

schema-h2.sql

CREATE TABLE users (id long PRIMARY KEY AUTO_INCREMENT, full_name VARCHAR(30), email VARCHAR(50));

I have tried using both these 2 urls enter image description here

enter image description here

Even "id" field is auto generated but I tried to add id also using postman.. But still getting the same error enter image description here

like image 590
Deepika Avatar asked Feb 22 '21 09:02

Deepika


People also ask

Why does spring boot say 404 error?

We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.


1 Answers

Your Sprint boot runner class, Application class is under com.hms.usermanagement.serverAPI.application package, so Spring boot will only scan the components under com.hms.usermanagement.serverAPI.application. So your core and web components are not recognized by Spring boot.

To solve the issue try to move Application.java class under com.hms.usermanagement.

Or you can customize the component scan by adding@ComponentScan annotation to Application.java class:

@SpringBootApplication
@ComponentScan(basePackages = "com.hms.usermanagement")
like image 147
Ismail Avatar answered Oct 22 '22 20:10

Ismail