How to persist LocalDate with JPA?

后端 未结 5 725
栀梦
栀梦 2020-12-04 01:22

I want to store Date without time into my database. So, I choose to use LocalDate type.

As mentioned in this article, I use a JPA converter to convert

5条回答
  •  一生所求
    2020-12-04 01:54

    Since this is a very common question, this answer is based on this article I wrote about the best way to map Date and Timestamp with JPA.

    JPA 2.2 added support for mapping Java 8 Date/Time API, like LocalDate, LocalTime, LocalDateTime, OffsetDateTime or OffsetTime.

    So, let's assume we have the following entity:

    @Entity(name = "UserAccount")
    @Table(name = "user_account")
    public class UserAccount {
    
        @Id
        private Long id;
    
        @Column(name = "first_name", length = 50)
        private String firstName;
    
        @Column(name = "last_name", length = 50)
        private String lastName;
    
        @Column(name = "subscribed_on")
        private LocalDate subscribedOn;
    
        //Getters and setters omitted for brevity
    }
    

    Notice that the subscribedOn attribute is a LocalDate Java object.

    When persisting the UserAccount:

    UserAccount user = new UserAccount()
        .setId(1L)
        .setFirstName("Vlad")
        .setLastName("Mihalcea")
        .setSubscribedOn(
            LocalDate.of(
                2013, 9, 29
            )
        );
    
    entityManager.persist(user);
    

    Hibernate generates the proper SQL INSERT statement:

    INSERT INTO user_account (
        first_name, 
        last_name, 
        subscribed_on, 
        id
    ) 
    VALUES (
        'Vlad', 
        'Mihalcea', 
        '2013-09-29', 
        1
    )
    

    When fetching the UserAccount entity, we can see that the LocalDate is properly fetched from the database:

    UserAccount userAccount = entityManager.find(
        UserAccount.class, 1L
    );
    
    assertEquals(
        LocalDate.of(
            2013, 9, 29
        ),
        userAccount.getSubscribedOn()
    );
    

提交回复
热议问题