Skip to content

Instantly share code, notes, and snippets.

@bind-disney
Created November 22, 2019 09:19
Show Gist options
  • Save bind-disney/eec02ae88e663c8899abb7e2d9f80bf3 to your computer and use it in GitHub Desktop.
Save bind-disney/eec02ae88e663c8899abb7e2d9f80bf3 to your computer and use it in GitHub Desktop.
Поддержка нативных ENUM-ов PostgerSQL в Spring Data JPA
package com.example.project.entity
import org.hibernate.annotations.Type
import org.hibernate.annotations.TypeDef
import com.example.project.enumeration.PostgreSQLEnumType
import com.example.project.enumeration.ModelStatus
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "models")
@TypeDef(name = "postgresql_enum", typeClass = PostgreSQLEnumType::class)
class Model(
@Id
val id: Int? = null,
@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition = "status")
@Type(type = "postgresql_enum")
val status: ModelStatus
)
package com.example.project.enumeration
/**
* Model status
*/
enum class ModelStatus {
DRAFT,
OPENED,
CLOSED,
ARCHIVED
}
package com.example.project.enumeration
import org.hibernate.HibernateException
import org.hibernate.engine.spi.SharedSessionContractImplementor
import org.hibernate.type.EnumType
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Types
class PostgreSQLEnumType : EnumType<Enum<*>?>() {
@Throws(HibernateException::class, SQLException::class)
override fun nullSafeSet(
statement: PreparedStatement,
value: Any?,
index: Int,
session: SharedSessionContractImplementor) {
val obj = if (value != null) (value as Enum<*>).name else null
statement.setObject(index, obj, Types.OTHER)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment