Posting data in a Spring Boot 2 Application with Spring Data JPA

Steffen Ebert :

I am trying to post data from postman via my Spring Boot 2 Application with Spring Data JPA into a MySQL Database. All I get is a 404 Error.

Main

@SpringBootApplication
public class ProfileApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProfileApplication.class, args);
    }

}

Entity

@Entity
public @Data class Profile {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String profileText;
}

Controller

@RestController
@RequestMapping(value = "/profile", produces = { MediaType.APPLICATION_JSON_VALUE })
public class ProfileController {

    @Autowired
    private ProfileRepository profileRepository;

    public ProfileRepository getRepository() {
        return profileRepository;
    }

    @GetMapping("/profile/{id}")
    Profile getProfileById(@PathVariable Long id) {
        return profileRepository.findById(id).get();
    }

    @PostMapping("/profile")
    Profile createOrSaveProfile(@RequestBody Profile newProfile) {
        return profileRepository.save(newProfile);
    }
}

Repository

public interface ProfileRepository extends CrudRepository<Profile, Long> {

}

application.propterties

server.port = 8080
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/profiledb
spring.datasource.username=root
spring.datasource.password=
server.servlet.context-path=/service

enter image description here

Alexandru Somai :

It seems that in your ProfileController, you have defined twice the profile endpoint (first at the class level, and second on the methods). The solution would be to remove one of them:

@RestController
@RequestMapping(value = "/profile", produces = { MediaType.APPLICATION_JSON_VALUE })
public class ProfileController {

    @Autowired
    private ProfileRepository profileRepository;

    public ProfileRepository getRepository() {
        return profileRepository;
    }

    // Notice that I've removed the 'profile' from here. It's enough to have it at class level
    @GetMapping("/{id}")
    Profile getProfileById(@PathVariable Long id) {
        return profileRepository.findById(id).get();
    }

    // Notice that I've removed the 'profile' from here. It's enough to have it at class level
    @PostMapping
    Profile createOrSaveProfile(@RequestBody Profile newProfile) {
        return profileRepository.save(newProfile);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12105&siteId=1