`@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="post_id")
private int id;
@Column(name="caption")
private String caption;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="post_date")
private Date postDate;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "post_id")
private List<Image> images;
@Column(name="likes")
private int Likes;
@Column(name="dislikes")
private int Dislikes;
@Column(name="pinned", columnDefinition = "boolean default false")
private boolean Pinned;
@OneToMany(mappedBy="post")
private List<Comment> comments;
}
`
`@Entity
@Table(name="images")
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="img_id")
private Long id;
@Column(name="img_name")
private String name;
@Column(name="img_url")
private String imageUrl;
}`
above is my two entities for my social media web application and below is postservice and postcontroller.
Controller code
`@GetMapping("/delete/{id}")
public String deletePost(@PathVariable("id") int id) {
postService.removePost(id);
return "redirect:/user/profile";
}`
Service code
`@Transactional
public void removePost(int id) {
Post p = postRepository.findById(id);
if (p != null) {
List<Image> images = p.getImages();
if (images != null && !images.isEmpty()) {
for (Image image : images) {
try {
Files.deleteIfExists(Paths.get(UPLOADED_FOLDER + image.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
postRepository.delete(p);
}
}`
in above case delete method of jparepository is not deleting the entity from the database for both image and post whereas images from the project folder is deleting.
i have already checked jparepository all methods create, read and update are working but only the delete is not working for the entities.
Sumit Gohil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.