Map PostgreSQL Interval Type in Hibernate
In this article
Mapping PostgreSQL's interval column type in Hibernate requires a custom type or a specific JPA attribute converter, because Hibernate does not natively map interval to a standard Java type. This guide shows you how to map it to a Duration (Java 8+) or a String for simple cases, and how to handle reads and writes correctly.
What You'll Need
- A PostgreSQL database with a table containing an
intervalcolumn. - A Java project with Hibernate 5.4+ or Hibernate 6.x (the approach works for both, with minor import differences).
- PostgreSQL JDBC driver (e.g.,
org.postgresql:postgresql) on your classpath. - Basic familiarity with JPA entities and annotations.
Step-by-Step
- Decide on the Java type. The most practical mapping is to
java.time.Duration, which represents a time-based amount (hours, minutes, seconds). If you only need to store the raw interval string (e.g., '1 day 02:03:04'), you can map it to aStringusing a simple converter. - Create an AttributeConverter for Duration. If you choose
Duration, create a class that implementsjavax.persistence.AttributeConverter<Duration, String>(orjakarta.persistencefor Hibernate 6). The converter will convertDurationto a PostgreSQL interval string and back.
Note: PostgreSQL accepts ISO 8601 duration strings likeimport javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.time.Duration; @Converter public class DurationToIntervalConverter implements AttributeConverter<Duration, String> { @Override public String convertToDatabaseColumn(Duration duration) { if (duration == null) return null; return duration.toString(); // e.g., PT1H30M } @Override public Duration convertToEntityAttribute(String dbData) { if (dbData == null) return null; return Duration.parse(dbData); } }PT1H30M. However, if you prefer a more human-readable format, you can format it manually (e.g., '1 hour 30 minutes'). For simplicity, the above uses the standard ISO format. - Apply the converter to your entity field. In your entity class, annotate the field with
@Convertand specify your converter class.
The@Entity public class Event { @Id @GeneratedValue private Long id; @Column(columnDefinition = "interval") @Convert(converter = DurationToIntervalConverter.class) private Duration duration; // getters and setters }columnDefinition = "interval"ensures Hibernate uses the correct column type when generating DDL. If you are not generating DDL from entities, you can omit it, but it's good practice to keep it. - Alternative: Map to String directly. If you only need to store the raw interval, you can skip the converter and just use a
Stringfield with@Column(columnDefinition = "interval"). Hibernate will map it as a varchar, but PostgreSQL will still store it as an interval. This is simpler but loses the ability to do arithmetic in Java. - Test the mapping. Write a simple JPA test to persist an entity with a
Durationand read it back. Verify that the value round-trips correctly. For example, persistDuration.ofHours(2).plusMinutes(30)and check the database value is '02:30:00' or 'PT2H30M' depending on your converter.
Common Mistakes
- Using the wrong converter import. In Hibernate 6, you must use
jakarta.persistenceinstead ofjavax.persistence. Mixing them causes class-not-found errors. - Forgetting the
@Converterannotation. Without it, Hibernate will not pick up the converter automatically. - Not specifying
columnDefinition. If you let Hibernate generate the schema, it might create avarcharcolumn instead ofinterval, which breaks the mapping. - Using
LocalTimeorLocalDateTimefor interval. These are not appropriate because interval represents a duration, not a point in time.
Tips
- If you need to store intervals with months or years (e.g., '1 year 2 months'),
Durationcannot represent them because it only handles hours/minutes/seconds. In that case, map toStringor use a custom class. - For better readability, you can customize the converter to output '1 day 02:03:04' format instead of ISO. PostgreSQL accepts both, but the ISO format is more standard.
- When using native queries, you can cast the interval to a string in SQL:
SELECT duration::text FROM eventto see the raw value. - Consider using Hibernate's built-in
org.hibernate.type.DurationTypeif you are on Hibernate 6.2+. It can mapDurationdirectly to an interval with@JdbcTypeCode(SqlTypes.INTERVAL_SECONDS).
Troubleshooting
Issue: Hibernate throws an error like "Could not determine type for column 'duration'"
This usually means the converter is not registered. Ensure your converter class is annotated with @Converter and is either in the same package as the entity or explicitly listed in persistence.xml or application.properties (e.g., spring.jpa.properties.hibernate.type_contributors).
Issue: The interval value is off by a few seconds or days.
PostgreSQL stores intervals with microsecond precision. If you use Duration which has nanosecond precision, you may lose precision. For most use cases, this is acceptable. If you need exact microsecond precision, consider mapping to a String or a custom class that stores the raw PostgreSQL interval string.
Issue: The column is created as varchar instead of interval.
Double-check that you have @Column(columnDefinition = "interval") on the field. If you are using Hibernate's auto-DDL, it should respect this. If not, you may need to run a manual ALTER TABLE to change the column type.
Issue: Reading a null interval returns an empty string.
Make sure your converter handles nulls correctly. In the convertToEntityAttribute, if dbData is null, return null. Also, ensure the column is nullable if you expect nulls.
Frequently Asked Questions
Can I map PostgreSQL interval to a Java Long (milliseconds)?
Yes, but you would need to write a converter that extracts total milliseconds from the interval. This is not recommended because you lose the ability to represent months and years accurately.
Does Hibernate 6 support interval natively?
Hibernate 6.2 introduced a DurationType that can map Duration to an interval with the @JdbcTypeCode(SqlTypes.INTERVAL_SECONDS) annotation. However, it still requires the column to be defined as interval in the database.
What is the difference between interval and timestamp?
interval represents a duration (e.g., '2 hours'), while timestamp represents a point in time (e.g., '2023-01-01 10:00:00'). They are not interchangeable.
Can I use Duration with JPA 2.2?
Yes, JPA 2.2 supports java.time types, but you still need a converter for Duration because it is not a standard mapped type. The converter approach works with any JPA implementation.
How do I query based on an interval column?
You can use JPQL with a parameter: SELECT e FROM Event e WHERE e.duration > :minDuration. The converter will handle the conversion automatically. For native queries, you may need to cast the parameter to interval.
Is it better to store intervals as strings?
Storing as a string is simpler but loses the ability to do date arithmetic in the database. If you only store and retrieve the value, a string is fine. If you need to compare or add intervals in SQL, use the native interval type.