I have a Spring Boot Hibernate Postgres application: https://github.com/TRahulSam1997/hibernate-spring-postgresql-project
Everything builds, and the application runs, but when I make any API calls, I get a 404 error. I cannot figure out what I've done wrong.
application.properties
file
spring.datasource.url=jdbc:postgresql://localhost:5432/users
spring.datasource.username=postgres
spring.datasource.password=root
spring.jpa.show-sql=true
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
server.servlet.context-path=/api/v1/
Main: HibernateSpringPostgresProjectApplication.java
package com.example.HibernateSpringPostgreSQLProject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HibernateSpringPostgresProjectApplication {
public static void main(String[] args) {
SpringApplication.run(HibernateSpringPostgresProjectApplication.class, args);
}
}
Model: Users.java
package model;
import javax.persistence.*;
@Entity
@Table(name = "users")
public class Users {
private long userId;
private String firstName;
private String lastName;
private String userName;
private String email;
public Users() {
// super();
}
public Users(String firstName, String lastName, String userName, String email) {
// super();
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.email = email;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "id", nullable = false)
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "user_name", nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "email_address", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [userId=" userId ", firstName=" firstName ", lastName=" lastName ", userName=" userName ", email=" email "]";
}
}
Controller: UsersController
package controller;
import exception.ResourceNotFoundException;
import model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import repository.UsersRepository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
//@RequestMapping("/v1")
public class UsersController {
@Autowired
private UsersRepository usersRepository;
// get users
@GetMapping("/users")
public List<Users> getAllUsers() {
return this.usersRepository.findAll();
}
// get user by id
@GetMapping("/user/{id}")
public ResponseEntity<Users> getUserById(@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
Users user = usersRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User with this id not found:: " userId));
return ResponseEntity.ok().body(user);
}
// save user
@PostMapping("/users")
public Users createUser(@Validated @RequestBody Users user) {
return usersRepository.save(user);
}
// update user
@PutMapping("/users/{id}")
public ResponseEntity<Users> updateUser(@PathVariable(value = "id") Long userId,
@Validated @RequestBody Users userDetails) throws ResourceNotFoundException {
Users user = usersRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User with this id not found:: " userId));
user.setEmail(userDetails.getEmail());
user.setFirstName(userDetails.getFirstName());
user.setLastName(userDetails.getLastName());
return ResponseEntity.ok(this.usersRepository.save(user));
}
//delete user
@DeleteMapping("/users/{id}")
public Map<String, Boolean> deleteUser(@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
Users user = usersRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User with this id not found:: " userId));
this.usersRepository.delete(user);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
JpaRepository: UsersRepository
package repository;
import model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UsersRepository extends JpaRepository<Users, Long> {
}
When I make a POST request through Postman, I get the following error:
POST Body:
{
"firstName": "John",
"lastName": "Doe",
"userName": "JohnDoe",
"email": "[email protected]"
}
Error:
{
"timestamp": "2022-04-19T00:31:39.464 00:00",
"status": 404,
"error": "Not Found",
"path": "/api/v1/users"
}
I'd appreciate any help!
CodePudding user response:
Try to uncomment the following line:
//@RequestMapping("/v1")
And send post request to /v1/users/
If you want to add "api" to url just change to this:
@RequestMapping("/api/v1")
And remember to change url in postman to /api/v1/users
CodePudding user response:
You're requesting the api with "/api/v1/users" as said in the error , while in the controller method and it is only @GetMapping "/users" so try to add "/api/v1" on the controller level e.g @RequestMapping("/api/v1")