Reputation: 97
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
Upvotes: 1
Views: 491
Reputation: 1405
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);
}
}
Upvotes: 4
Reputation: 1733
Which url? Valid url must look like:
GET: http://localhost:8080/service/profile/profile/1
POST: http://localhost:8080/service/profile/profile
Upvotes: 1