1

This doesn't feel very DRY at all.

I have an SQL script that generates all of my database tables, so I have a lot of redundant annotations in my @Entity class.

For example,

@Column(unique = true, length = 254)
@NotNull
private String email;

or auto increment logic such as

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

All of these field annotations are redundant considering in the SQL I have already declared such things.

Is there any reason to keep these annotations around? From what I understand, any kind of serious application should be using SQL scripts to create the database tables anyways, and it sure would be nice to have less noise in the classes I'm writing.

Bassinator
  • 1,682
  • 3
  • 23
  • 50

2 Answers2

2

there are two type of annotations (DDL and validation types) in your example:

@Column(unique = true, length = 254)
@NotNull
  1. @NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. It's used by validation processor and doen't connected with DB. so it's not redundant in your mapping. But , for example

    @Column(nullable = false) - it gives the jpa provider hints to generate the right DDL for creating table columns with the database constraints

2.@Column(unique = true, length = 254) they are hints for ddl that hibernate generate.

BUT for @Column(updatable = false, name = "flight_name", nullable = false, length=50) updatable - it's not ddl , it's optimization.

from hibernate docs

@Column(
    ddl/mapping : name="columnName"; 
    optimization: boolean insertable() default true;
    optimization: boolean updatable() default true;
    ddl/mapping  : String table() default "";
    DDL -->: boolean unique() default false;
    DDL -->: boolean nullable() default true;
    DDL -->: String columnDefinition() default "";
    DDL -->: int length() default 255;
   ......
)

If you use ddl scripts all hibernate ddl-annotation attributes are redundant (if you use in memory tests , there will be autogenaration for in-memory db ), and will be used only if you configured hibernate.hbm2ddl.auto option in hibernate/jpa config. Also it's very dangerous scenarios when you give hibernate permission to do DDL in production.

for work with production : see liquibase , flywaydb for DDL.

xyz
  • 5,228
  • 2
  • 26
  • 35
-1

Two reasons that come to my mind:

  1. They can be useful in integration tests when you let hibernate create and drop schema in an in-memory database that is used in tests.
  2. Very few of them are also used by Hibernate in runtime to make some optimizations, like optional = false (not null) in combination with @PrimaryKeyJoinColumn for one-to-one associations when Hibernate knows that it is safe to make a proxy for lazy association instead of switching to eager loading.
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110