Skip to content

Instantly share code, notes, and snippets.

@jpmsilva
Created February 18, 2021 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmsilva/0bd709492d369a6f4296b2e7f929eb1d to your computer and use it in GitHub Desktop.
Save jpmsilva/0bd709492d369a6f4296b2e7f929eb1d to your computer and use it in GitHub Desktop.
Joda time type contributor for Jadira+Hibernate
/*
* Copyright 2018 Joao Silva
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.vilt.domain.entities.types
import org.hibernate.boot.model.TypeContributions
import org.hibernate.boot.model.TypeContributor
import org.hibernate.service.ServiceRegistry
import org.hibernate.usertype.CompositeUserType
import org.hibernate.usertype.UserType
import org.jadira.usertype.dateandtime.joda.*
import org.jadira.usertype.spi.utils.reflection.ClassLoaderUtils
/**
* Register by creating META-INF/services/org.hibernate.boot.model.TypeContributor
* and add io.vilt.domain.entities.types.JodaTimeTypeContributor to that file.
*/
class JodaTimeTypeContributor : TypeContributor {
override fun contribute(typeContributions: TypeContributions?, serviceRegistry: ServiceRegistry?) {
getTypes().forEach { typeContributions?.contributeType(it, it.returnedClass().name) }
getCompositeUserTypes().forEach { typeContributions?.contributeType(it, it.returnedClass().name) }
}
private fun getTypes(): List<UserType> =
if (hasJodaTime) {
listOf(
PersistentDateTime(),
PersistentDurationAsString(),
PersistentInstantAsTimestamp(),
PersistentLocalDate(),
PersistentLocalDateTime(),
PersistentLocalTime(),
PersistentMonthDayAsString(),
PersistentPeriodAsString(),
PersistentTimeOfDay(),
PersistentYearMonthDay(),
PersistentYears(), PersistentMinutes()
)
} else {
emptyList()
}
private fun getCompositeUserTypes(): List<CompositeUserType> =
if (hasJodaTime) {
listOf(PersistentDateMidnight(), PersistentInterval())
} else {
emptyList()
}
companion object {
private val hasJodaTime = try {
Class.forName("org.joda.time.DateTime", false, ClassLoaderUtils.getClassLoader())
true
} catch (e: ClassNotFoundException) {
false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment