im using spring boot and CrudRepository for my queries, the project is about posting content on a blog, so I have a post record with id, creator name, post name, the content itself likes and dislikes:
import org.springframework.data.annotation.Id;
public record Post(
@Id
Integer id,
String creatorName,
String postName,
String content,
int likes,
int dislikes
) {
}
this is my PostController to set GET, SET, PUT etc... requests
@RestController
@RequestMapping("/api/posts")
public class PostController {
//private final PostRepository repository;
private final AccessingPostDataMySql repository;
@Autowired
public PostController(AccessingPostDataMySql repository) {
this.repository = repository;
}
@GetMapping
public List<Post> findAll() {
System.out.println(repository);
return (List<Post>) repository.findAll();
}
@GetMapping("/{id}")
public Iterable<Post> findById(@PathVariable Iterable<Integer> id) {
return repository.findAllById(id);
}
@PostMapping
public void insertPost(@RequestBody Post post) {
System.out.println(post.postName());
repository.save(post);
}
@PutMapping("/likes/{id}")
public int addLike(@PathVariable Integer id) throws Exception {
repository.addLike();
return 1;
}
@PutMapping("/dislikes/{id}")
public int addDislike(@PathVariable Integer id) throws Exception {
repository.addDislike();
return 1;
}
}
and for the repository I have the PostRepository interface extending CrudRepository to query my data base (which is MySql)
public interface AccessingPostDataMySql extends CrudRepository<Post, Integer> {
@Modifying
@Query("UPDATE post SET likes = likes + 1")
void addLike();
@Modifying
@Query("UPDATE post SET dislikes = dislikes + 1")
void addDislike();
}
now my question is does CrudRepository work well against SQL injections?, I also had to set up like and dislike queries myself as you can see, are those queries vulnerable to SQL injections? if so how can I protect my project against it?