12

I have a table GameCycle in a db that holds a column date of type number. The values in this column are 8-digit numbers representing an inverse date like '20130301'. Mapped onto this table i have a class GameCycle that holds a protected field iDate of type java.util.Date. That field is annotated '@Type(type = "inverseDate")', using a custom type mapping. The class Gamecycle is annotated with '@TypeDef(name = "inverseDate", typeClass = InverseDateType.class)'

import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

@Entity
@TypeDef(name = "inverseDate", typeClass = InverseDateType.class)
@Table(name = "GAMECYCLE")
public class GameCycle implements Comparable<GameCycle>, Serializable
{
    @Type(type = "inverseDate")
    @Column(name = "GC_DATE", nullable = false)
    protected Date iDate = null;
    ...

Obviously, the imports bind me to using hibernate as a jpa implementation so my question is:

Is there a way to get rid of the hibernate annotations and do the same custom type mapping using a pure javax.persistence solution ?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
tyler
  • 193
  • 1
  • 3
  • 11

2 Answers2

47

Custom Type Mapping has been finally added in JPA 2.1 (JSR-388, part of Java EE 7).
The Hibernate's @Type annotation is no longer needed, and can be replaced by Type Conversion in JPA 2.1.

JPA 2.1 has added :

The most basic example : (Example 1: Convert a basic attribute) - from source

@Converter
public class BooleanToIntegerConverter 
    implements AttributeConverter<Boolean, Integer> 
{  ... }

...

@Entity
@Table(name = "EMPLOYEE")
public class Employee
{

    @Id
    private Long id;

    @Column
    @Convert(converter = BooleanToIntegerConverter.class)
    private boolean fullTime;

}

Other links :

Daniel Gray
  • 1,697
  • 1
  • 21
  • 41
Guillaume Husta
  • 4,049
  • 33
  • 40
8

No. Current version of JPA specification doesn't support custom type mappings. It's one of the most wanted features for future JPA 2.1.

If you really want to get rid of Hibernate-specific annoations, the only thing you can do is to map your field as String and perform necessary conversion manually (in getters/setters).

But in practice almost every large JPA-based application uses some implementation-specific features of persistence provider, therefore I don't think that avoiding dependency on Hibernate in this case really matters.

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Too bad, i had suspected that the only solution besides being bound to an implementation would be some conversion in the getters/setters. Thank you for the quick answer though. – tyler Apr 15 '13 at 07:05