I am trying to do a simple data insert to H2 database, but I end up getting the error
Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.carepay.assignment.domain.Post'
My controller
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
PostDetails createPost(@Valid @RequestBody CreatePostRequest createPostRequest) {
return postService.createPost(createPostRequest);
}
My service
public interface PostService {
PostDetails createPost(@Valid CreatePostRequest createPostRequest);
Page<PostInfo>getPosts(final Pageable pageable);
PostDetails getPostDetails(Long id);
void deletePost(Long id);
}
My Implementation
this is where am getting the error
@Service
public class PostServiceImpl implements PostService {
@Autowired
private PostRepository postRepository;
@Override
public PostDetails createPost(@Valid CreatePostRequest createPostRequest) {
CreatePostRequest createResponse = postRepository.save(createPostRequest);
return createResponse;
}
my repository
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
my domain classes
My createPostRequest class
public class CreatePostRequest {
private String title;
private String content;
}
My PostDetails class
public class PostDetails extends PostInfo {
private String content;
}
My PostInfo class
public class PostInfo {
private Long id;
private String title;
}
and my Post model
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String content;
}
How can I get the API to post data to the database. I have researched no luck. Thank you in adavance
CodePudding user response:
In your PostService you are trying to save a CreatePostRequest in
CreatePostRequest createResponse = postRepository.save(createPostRequest);
However your PostRepository knows about Post and not CreatePostRequest. You have to extract the Post object from CreatePostRequest and pass it to the save method of your repository.
Moreover your method returns the same type of CreatePostRequest => CreatePostRequest createResponse = ... instead of PostDetails.
Below I changed the createPost method you just have to put the missing parts
@Override
public PostDetails createPost(@Valid CreatePostRequest createPostRequest) {
Post post = new Post();
post.setTitle(createPostRequest.getTitle());
post.setContent(createPostRequest.getContent());
Post savedPost = postRepository.save(post);
PostDetails postDetails = new PostDetails();
postDetails.setId(savedPost.getId());
postDetails.setTitle(savedPost.getTitle());
postDetails.setContent(savedPost.getContent());
return postDetails;
}
