1 package de.juplo.jpa.converters;
3 import de.juplo.jpa.converters.TimeConversions.FixedZoneIdStrategy;
4 import de.juplo.jpa.converters.TimeConversions.FixedZoneOffsetStrategy;
5 import java.time.OffsetDateTime;
6 import java.time.ZoneId;
7 import java.time.ZoneOffset;
8 import java.time.ZonedDateTime;
9 import javax.persistence.EntityManager;
10 import javax.persistence.EntityTransaction;
11 import javax.persistence.Persistence;
12 import org.junit.Test;
13 import static org.junit.Assert.assertEquals;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
22 public class JPAConverterTest
24 final static Logger log = LoggerFactory.getLogger(JPAConverterTest.class);
29 ZonedDateTime zdt = ZonedDateTime.now();
30 OffsetDateTime odt = OffsetDateTime.now();
32 ZoneId defaultZone = ZoneId.systemDefault();
33 ZoneId otherZone = defaultZone.getId().equals("America/New_York") ? ZoneId.of("Europe/Berlin") : ZoneId.of("America/New_York");
35 ZoneOffset defaultOffset = defaultZone.getRules().getOffset(odt.toLocalDateTime());
36 ZoneOffset otherOffset = ZoneOffset.ofTotalSeconds(defaultOffset.getTotalSeconds() + 3 * 60 * 60);
40 public void testOffsetDateTimeAnnotated()
42 em = Persistence.createEntityManagerFactory("annotated").createEntityManager();
47 public void testOffsetDateTimeXml()
49 em = Persistence.createEntityManagerFactory("xml").createEntityManager();
53 public void testOffsetDateTime()
55 EierlegendeWollmilchSau ews;
57 TimeConversions.setZoneOffsetStrategy(new FixedZoneOffsetStrategy(defaultOffset));
58 ews = new EierlegendeWollmilchSau();
61 ews = retrieve(EierlegendeWollmilchSau.class, ews.id);
62 assertEquals(odt, ews.odt);
64 TimeConversions.setZoneOffsetStrategy(new FixedZoneOffsetStrategy(otherOffset));
65 ews = new EierlegendeWollmilchSau();
68 ews = retrieve(EierlegendeWollmilchSau.class, ews.id);
69 assertEquals(odt.toInstant(), ews.odt.toInstant());
74 public void testZonedDateTimeAnnotated()
76 em = Persistence.createEntityManagerFactory("annotated").createEntityManager();
81 public void testZonedDateTimeXml()
83 em = Persistence.createEntityManagerFactory("xml").createEntityManager();
87 public void testZonedDateTime()
89 EierlegendeWollmilchSau ews;
91 TimeConversions.setZoneIdStrategy(new FixedZoneIdStrategy(defaultZone));
92 ews = new EierlegendeWollmilchSau();
95 ews = retrieve(EierlegendeWollmilchSau.class, ews.id);
96 assertEquals(zdt, ews.zdt);
98 TimeConversions.setZoneIdStrategy(new FixedZoneIdStrategy(otherZone));
99 ews = new EierlegendeWollmilchSau();
102 ews = retrieve(EierlegendeWollmilchSau.class, ews.id);
103 assertEquals(zdt.toInstant(), ews.zdt.toInstant());
107 private void persist(Object entity)
109 EntityTransaction tx = em.getTransaction();
112 log.info("persisting {}", entity);
117 private <T> T retrieve(Class<T> entityClass, Object id)
119 EntityTransaction tx = em.getTransaction();
123 log.info("retrieving {} of class {}", id, entityClass);
124 return em.find(entityClass, id);