简体   繁体   中英

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 .

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.

Theoretically it should be something like this:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.persistence.Id;
import javax.persistence.TableGenerator;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomIdAnnotation {

    TableGenerator generator() default @TableGenerator(name = "EVENT_GEN", 
            table = "SEQUENCES", 
            pkColumnName = "SEQ_NAME", 
            valueColumnName = "SEQ_NUMBER", 
            pkColumnValue = "ID_SEQUENCE", 
            allocationSize = 1);

    Id id();
}

However, I think that this will not work because the persistence provider (Hibernate, EclipseLink,etc..) processes annotations of package javax.persistence.* + provider specific annotations directly in your entity class. So this may work if you plan to write your own persistence provider. ( implementing JSR-000338 JPA 2.1 specification )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM