Skip to content

Instantly share code, notes, and snippets.

@tamboer
Last active December 18, 2017 13:52
Show Gist options
  • Select an option

  • Save tamboer/ff2b3df6ba898df717a0f1bd13fa5daa to your computer and use it in GitHub Desktop.

Select an option

Save tamboer/ff2b3df6ba898df717a0f1bd13fa5daa to your computer and use it in GitHub Desktop.
Converts LocalDate for Db
/**
@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();
}
}
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