I was creating a blog which is almost finished. Everything worked ok with LocalDate until one point, when the admin creates a post a "creation date" and a "modified date" are added to that post which is saved in the MySQL database. Every time the user updates the post the "modified" date is changed.
One of the last functionalities I wanted to add was displaying the last 3 posts that where posted by the admin in a descending order. Now here is the problem: If the admin adds 3 post in the same day one after the other, then LocalDate is not able to sort them since it cannot distinguish between them since all have the same standard date, and the time is absent.
I tried modifying my JPA queries and every entity field and method to use LocalDateTime instead of LocalDate, but then this happens:
@Repository
public interface PostRepository extends CrudRepository<Post, Long> {
List<Post> findAllByCreatedAtBetween(LocalDateTime start, LocalDateTime end);
List<Post> findAllByOrderByCreatedAtDesc();
}
java.lang.IllegalArgumentException: Parameter value [2020-09-01T12:27:19.341] did not match expected type [java.time.LocalDate (n/a)]
I read somewhere that 'between' does not work with LocalDateTime, now my whole project is broken.
I am confused and really annoyed I found out so late that LocalDate was the wrong choice in term of flexibility. Please help me understand what options do I have now in order to make that functionality work. Any help would be greatly appreciated!
The Post class:
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime createdAt;
private LocalDateTime modifiedAt;
@NotBlank(message = "Post Title is required")
private String title;
@Basic(fetch = FetchType.LAZY)
private String image;
@Column(length = 65535,columnDefinition="Text")
@NotBlank(message = "Post Content is required")
private String content;
@OneToMany(cascade = CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "POST_TAG", joinColumns = {@JoinColumn(name = "post_id")},
inverseJoinColumns = {@JoinColumn(name = "tag_id")})
private Set<Tag> tags = new HashSet<>();
For anyone struggling with the same issue, it is easier this time, instead of doing modifications that break the whole code to just sort the entities by ID. But next time pick a class that offers you more flexibility (like LocalDateTime) from the start since you never know what you need to implement down the line.