Custom @Column JPA Annotations, how to?
Asked Answered
A

1

4

Been trying hard to search for a solution to create some Custom JPA Annotations to replace repetitive fields when declaring Entity POJOs. Any help? Here what I am trying to achieve:

//@Column(name = "is_enabled", nullable = false, columnDefinition = "tinyint(1) DEFAULT 1")
@ColumnBooleanNotNullDefaultOne
private Boolean isEnabled;

or

//@Column(name = "created", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
@ColumnTimestamp
private Timestamp created;

However, my attempts are failing...

@Target({METHOD, FIELD})
@Retention(RUNTIME)
@Column // <-- Error here (The annotation @Column is disallowed for this location.)
public @interface BooleanNotNullDefaultOne
{

}

Any help is definatelly aprecciated.

Thank you!

Arlin answered 28/4, 2014 at 16:31 Comment(0)
S
0

Generate a new Class that implements UserType and use this annotation:

@Type(type="fully.qualified.name.of.YourUserType")

Also, the @Column annotation can only be used on a method or variable. Take a look at the @Target of the Column interface definition to understand why.

Sacramentarian answered 28/4, 2014 at 16:39 Comment(4)
It's funny how Hibernate asks you to implement 11 methods for your "UserType" and in the end, you have to @Type("giganticQualifiedClassPath"), but I will def take a look at it. I appreciate your help.Arlin
There is a way to create a short name for those, but I never bothered to figure it out. Good luck!Sacramentarian
Maybe import the annotation class?Cruse
I suppose you could do @Type(type=YourUserType.class.getName()), but then you're counting on the fact that the custom type would be loaded before the entity.Sacramentarian

© 2022 - 2024 — McMap. All rights reserved.