Search code examples
javajpaannotations

How to combine annotations for hibernate mapping?


Assuming that (using JPA) I have an entity with an id:

...
@Id
@TableGenerator(name = "EVENT_GEN",
                table = "SEQUENCES",
                pkColumnName = "SEQ_NAME",
                valueColumnName = "SEQ_NUMBER",
                pkColumnValue = "ID_SEQUENCE",
                allocationSize=1)
private Long id;
...

how can I declare a custom annotation so the above id mapping will be :

@CustomIdAnnotation
private Long id

May be something like this SO answer.


Solution

  • As Neil Stockton mention, the meta annotation will probably be a part of next JPA version 2.2.

    And for now, with JPA 2.1, I can use @Embeddable class for both id (@EmbeddedId) and non-id field (@Embedded)

    Just to note that for @Embeddable, I can use a generic class, so it will be useful for any type + I can easily override my column attributes:

    @Embeddable
    @Getter @Setter @NoArgsConstructor // Lombok library
    public class EmbeddableGeneric<T> {
        @Column 
        // other annotations
        T myField;
        
        ...
    }
    

    and in my entity class:

    @Entity
    @Getter @Setter @NoArgsConstructor // You know now what's this!
    public class Person {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @Embedded
        @AttributeOverride(name = "myField", column = @Column(name = "STRING_FIELD"))
        private EmbeddableGeneric<String> myString;
    
    ...
    }
    

    Let's wait for JPA 2.2 to overcome this verbosity.