Last active
December 18, 2017 13:52
-
-
Save tamboer/ff2b3df6ba898df717a0f1bd13fa5daa to your computer and use it in GitHub Desktop.
Converts LocalDate for Db
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| @Column | |
| @Convert(converter = LocalDateConverter.class) | |
| private LocalDate dateOfBirth; | |
| */ | |
| import javax.persistence.AttributeConverter; | |
| import javax.persistence.Converter; | |
| import java.sql.Date; | |
| import java.time.LocalDate; | |
| @Converter(autoApply = true) | |
| public class LocalDateConverter implements AttributeConverter<LocalDate, Date> { | |
| @Override | |
| public Date convertToDatabaseColumn(LocalDate localDate) { | |
| return localDate == null ? null : Date.valueOf(localDate); | |
| } | |
| @Override | |
| public LocalDate convertToEntityAttribute(Date sqlDate) { | |
| return sqlDate == null ? null : sqlDate.toLocalDate(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.tvh.organizations.member.converter; | |
| import org.junit.Before; | |
| import org.junit.Test; | |
| import org.junit.runner.RunWith; | |
| import org.mockito.runners.MockitoJUnitRunner; | |
| import java.sql.Date; | |
| import java.time.LocalDate; | |
| import static org.assertj.core.api.Assertions.assertThat; | |
| @RunWith(MockitoJUnitRunner.class) | |
| public class LocalDateConverterTest { | |
| private final static LocalDate LOCAL_DATE = LocalDate.of(1975, 03, 01); | |
| private final static Date DATE = Date.valueOf("1975-03-01"); | |
| private LocalDateConverter localDateConverter; | |
| @Before | |
| public void setup() { | |
| localDateConverter = new LocalDateConverter(); | |
| } | |
| @Test | |
| public void convertToDatabaseColumnConvertsCorrectly() { | |
| Date result = localDateConverter.convertToDatabaseColumn(LOCAL_DATE); | |
| assertThat(result).isEqualTo(DATE); | |
| } | |
| @Test | |
| public void convertToDatabaseColumnConvertsNullToNull() { | |
| Date result = localDateConverter.convertToDatabaseColumn(null); | |
| assertThat(result).isNull(); | |
| } | |
| @Test | |
| public void convertToEntityAttributeConvertsCorrectly() { | |
| LocalDate result = localDateConverter.convertToEntityAttribute(DATE); | |
| assertThat(result).isEqualTo(LOCAL_DATE); | |
| } | |
| @Test | |
| public void convertToEntityAttributeConvertsNullToNull() { | |
| LocalDate result = localDateConverter.convertToEntityAttribute(null); | |
| assertThat(result).isNull(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment