Skip to content
Advertisement

What to use: sql migration or entity setups in Spring/Hibernate?

I am little confused, when see, why most programmers use annotation-based setup for database table constraints. For example

@Column(unique=true, nullable=false)

Why do we need that, if(as I heard) in real projects mostly used SQL migrations, so you are able to create this constraints in table creations, like CREATE table... name varchar UNIQUE NOT NULL.

Do I need to setup it in both ways, or is it enough to do in SQL? And how often SQL migrations used(Flyway, Liquibase) in projects?

Additionally, Hibernate creates unreadable constraints in database, otherwise in SQL you create understandable names of constrains.

Advertisement

Answer

You can choose whether to let Hibernate to manage your schema or not. If yes , the database schema will be created or updated based on the changes of the annotation mapping.

I personally will not let Hibernate to manage my database schema as I want to be exactly know what is going on with the schema changes . The hibernate documentation also suggests it somehow:

Although the automatic schema generation is very useful for testing and prototyping purposes, in a production environment, it’s much more flexible to manage the schema using incremental migration scripts.

while Flyway, Liquibase is the kind of incremental migration scripts tool.

Do I need to setup it in both ways, or is it enough to do in SQL? And how often SQL migrations used(Flyway, Liquibase) in projects?

If you do not use the automatic schema generation feature , you don’t need to specify unique in @Column which only has meaning in case of automatic schema generation.

For nullable , it depends on hibernate.check_nullability setting.If it is turned on and you set @Column(nullable=false) , Hibernate will help to check this column cannot be null in the application level without asking the DB to check it. But even if do not set it , the database constraint (assuming you create a non-null constraint for it in DB) will eventually check it and not allow you to save the null value

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement