0

Jakarta EE

@Entity(name = "Book")
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String isbn;

    private String title;

    @Column(name = "published_on", columnDefinition = "date")
    @Convert(converter = YearMonthDateAttributeConverter.class)
    private YearMonth publishedOn;

    // Getters and setters omitted for brevity
}

I want to insert Year and Month only and I'm using JakartaEE Jsonb. Localdate is working fine but i have to insert the day too. I don't wont to use Jackson.

JEE JSON Binding

public class Book {

    public String isbn;
    public String title;
    public YearMonth publishedOn;

}

public static void main(String[] args) {

        // Create a book instance
        Book book = new Book();
        book.isbn = "123";
        book.title = "Advanced JPA and Hibernate";
        book.publishedOn = YearMonth.of(2022, 9);

        // Create Jsonb and serialize
        Jsonb jsonb = JsonbBuilder.create();
        var result = jsonb.toJson(book);
}
  • It's not clear wtaht the problem is; please add more details about the problems you are facing – Luca Basso Ricci Aug 31 '22 at 06:52
  • @LucaBassoRicci thanks for your comment, I have updated the question added another example and the link for the JSON Binging spec for more details. https://javaee.github.io/jsonb-spec/ – Abdelmuniem Sep 02 '22 at 05:48
  • I'm still in trouble understanding the real problem, but if your concerns are about using a `date` column in database that's not a big deal: just throw out day from data column (https://stackoverflow.com/questions/43059147/how-to-map-java-time-year-and-others-java-time-types-using-hibernate) – Luca Basso Ricci Sep 02 '22 at 06:02
  • Thanks @LucaBassoRicci my problem is related to JSONB serialization and is very clear if you have an experience in Jakarta EE jsonb spec. – Abdelmuniem Sep 02 '22 at 06:15

1 Answers1

0

I found a solution to my answer by creating YearMonthTypeAdapter implementing the JsonAdapter<YearMonth, String> class, then overrode the below methods:

  1. String adaptToJson(YearMonth date) return date.toString;
    
  2. YearMonth adaptFromJson(String string) return YearMonth.parse(string);
    
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77