Spring Boot 500 Internal Server Error with Post method

57 views Asked by At

I'm having trouble with POST. I am trying to add an post to the postgresql datebase using the Post method but constantly get the 500 internal Server Error. Why am I getting the error? and How do I fix It?

Client class


@Entity
@Table(name ="client")
@Data
public class Client {
    @Id
    @SequenceGenerator(
            name = "client_sequence",
            sequenceName = "client_sequence",
            allocationSize = 1
    )

    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "client_sequence"
    )
    private Long id;

    private String clientName;
    private String password;

    public Client(String clientName, String password) {
        this.clientName = clientName;
        this.password = password;
    }

    public Client() {

    }


}

Client Controller


@RestController
@RequestMapping("/client")
public class ClientController {

    private final ClientService clientService;
    @Autowired
    public ClientController(ClientService clientService) {
        this.clientService = clientService;
    }

    @GetMapping
    public List<Client> getAllClient(){
        return clientService.getAllClient();
    }

    @PostMapping
    public Client createClient(@RequestBody Client newClient){
        return clientService.saveOneClient(newClient);
    }

    @GetMapping("/{clientId}")
    public Client getOneClient(@PathVariable Long clientId){
        return clientService.getOneClient(clientId);
    }

    @PutMapping("/{clientId}")
    public Client updateOneClient(@PathVariable Long clientId, @RequestBody Client newClient){
        return clientService.updateOneClient(clientId, newClient);
    }

    @DeleteMapping("/{clientId}")
    public void deleteOneClient(@PathVariable Long clientId){
        clientService.deleteById(clientId);
    }
}

client service


@Service
public class ClientService {
    private final ClientRepository clientRepository;
    public ClientService(ClientRepository clientRepository) {
        this.clientRepository = clientRepository;
    }

    public List<Client> getAllClient() {
        return clientRepository.findAll();
    }

    public Client saveOneClient(Client newClient) {
        return clientRepository.save(newClient);
    }

    public Client getOneClient(Long clientId) {
        return clientRepository.findById(clientId).orElse(null);
    }

    public Client updateOneClient(Long clientId, Client newClient) {
        Optional<Client> client = clientRepository.findById(clientId);
        if(client.isPresent()){
            Client foundClient = client.get();
            foundClient.setClientName(newClient.getClientName());
            foundClient.setPassword(newClient.getPassword());
            clientRepository.save(foundClient);
            return foundClient;
        }else
            return null;
    }

    public void deleteById(Long clientId) {
        clientRepository.deleteById(clientId);
    }
}

post class


@Entity
@Table(name ="post")
@Data
public class  Post {
    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "client_id",nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    Client client;

    private String title;
    @Lob
    @Column(columnDefinition = "text")
    private String text;
}

post controller


@RestController
@RequestMapping("/posts")
public class PostController {
    private final PostService postService;

    @Autowired
    public PostController(PostService postService) {
        this.postService = postService;
    }

    @GetMapping
    public List<Post> getAllPosts(@RequestParam Optional<Long> clientId){
        return postService.getAllPosts(clientId);
    }
    @PostMapping
    public Post createOnePost(@RequestBody PostCreateRequest newPostRequest){
        return postService.createOnePost(newPostRequest);
    }
    @GetMapping("/{postId}")
    public Post getOnePost(@PathVariable Long postId){
        return postService.getOnePostById(postId);
    }

}

post service

@Service
public class PostService {
    private final PostRepository postRepository;
    private final ClientService clientService;
    @Autowired
    public PostService(PostRepository postRepository, ClientService clientService) {
        this.postRepository = postRepository;
        this.clientService = clientService;
    }

    public List<Post> getAllPosts(Optional<Long> clientId) {
        if(clientId.isPresent()) {
            return  postRepository.findByClientId(clientId.get());
        }else
           return postRepository.findAll();
    }

    public Post getOnePostById(Long postId) {
        return postRepository.findById(postId).orElse(null);
    }

    public Post createOnePost(PostCreateRequest newPostRequest) {
        Client client;
        client = clientService.getOneClient(newPostRequest.getUserId());
        if (client == null){
            return  null;
        }
        Post toSave = new Post();
        toSave.setId(newPostRequest.getId());
        toSave.setText(newPostRequest.getText());
        toSave.setTitle(newPostRequest.getTitle());
        toSave.setClient(client);
        return postRepository.save(toSave);
    }
}

postRepository

public interface PostRepository extends JpaRepository<Post,Long> {

    List<Post> findByClientId(Long aLong);
}

PostCreateRequest

@Data
public class PostCreateRequest {
    Long id;
    String text;
    String title;
    Long userId;

}

config

@Configuration
public class ClientConfig {

    @Bean
    CommandLineRunner commandLineRunner(ClientRepository repository){
        return args->{
            Client ab = new Client(
                    "ab",
                    "123"
            );
            Client ac = new Client(
                    "ac",
                    "234"
            );

            repository.saveAll(
                    List.of(ab, ac)
            );
        };
    }
}

applicationproperties

spring.jpa.hibernate.ddl-auto= update
spring.datasource.url=jdbc:postgresql://localhost:5432/client
spring.datasource.username=
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true

POST method

POST http://localhost:8080/posts
Content-Type: application/json

{"client_id": 1,
"id":1,
"title": "sadsadas",
"text": "123123"}

error in intellij java.lang.IllegalArgumentException: The given id must not be null error in postman { "timestamp": "2024-02-15T17:55:45.989+00:00", "status": 500, "error": "Internal Server Error", "trace":..

1

There are 1 answers

0
Murat K. On

Since JPA creates id automatically, you can try to remove id from POST body, createOnePost method and PostCreateRequest class.