1 package com.vladmihalcea.hibernate.type.interval;
2
3 import com.vladmihalcea.hibernate.type.ImmutableType;
4 import org.hibernate.engine.spi.SharedSessionContractImplementor;
5 import org.postgresql.util.PGInterval;
6
7 import java.sql.PreparedStatement;
8 import java.sql.ResultSet;
9 import java.sql.SQLException;
10 import java.sql.Types;
11 import java.time.Duration;
12 import java.time.Period;
13
14 /**
15  * Maps a Java {@link Duration} object to a PostgreSQL Interval column type.
16  *
17  * @author Jan-Willem Gmelig Meyling
18  * @author Vlad Mihalcea
19  * @since 2.6.2
20  */

21 public class PostgreSQLPeriodType extends ImmutableType<Period> {
22
23     public static final PostgreSQLPeriodType INSTANCE = new PostgreSQLPeriodType();
24
25     public PostgreSQLPeriodType() {
26         super(Period.class);
27     }
28
29     @Override
30     protected Period get(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException {
31         final PGInterval interval = (PGInterval) rs.getObject(names[0]);
32
33         if (interval == null) {
34             return null;
35         }
36
37         final int years = interval.getYears();
38         final int months = interval.getMonths();
39         final int days = interval.getDays();
40
41         return Period.ofYears(years)
42                 .plusMonths(months)
43                 .plusDays(days);
44     }
45
46     @Override
47     protected void set(PreparedStatement st, Period value, int index, SharedSessionContractImplementor session) throws SQLException {
48         if (value == null) {
49             st.setNull(index, Types.OTHER);
50         } else {
51             final int days = value.getDays();
52             final int months = value.getMonths();
53             final int years = value.getYears();
54             st.setObject(index, new PGInterval(years, months, days, 0, 0, 0));
55         }
56     }
57
58     @Override
59     public int[] sqlTypes() {
60         return new int[]{Types.OTHER};
61     }
62
63 }
64