Публикация данных в приложении Spring Boot 2 с помощью Spring Data JPA - PullRequest
1 голос
/ 26 февраля 2020

Я пытаюсь отправить данные почтальона через приложение Spring Boot 2 с Spring Data JPA в базу данных MySQL. Все, что я получаю, это ошибка 404.

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;
}

Контроллер

@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);
    }
}

Хранилище

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

Ответы [ 2 ]

4 голосов
/ 26 февраля 2020

Кажется, что в вашем ProfileController вы дважды определили конечную точку profile (сначала на уровне класса, а затем на методах). Решение было бы удалить один из них:

@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);
    }
}
1 голос
/ 26 февраля 2020

Какой URL? Действительный URL должен выглядеть следующим образом:

GET: http://localhost: 8080 / служба / профиль / профиль / 1

POST: http://localhost: 8080 / сервис / профиль / профиль

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...