1

I have seen instances where developers create tables in the database then they use jpa tools to generate entities from the tables. There are also cases where entities are first created then the tables will be created by the JPA provider. Which is the best approach?

When I learnt java ee web I used the jpa provider to create entities for me in the database.

  • Keep both activities separated. Use something like flyway or liquibase to maintain the database. Model the objects properly and then figure out how to map those objects to the database. I would suggest to read a book such as `Implementing Domain-Driven Design` to understand what are the good practices around this. – Augusto Jan 25 '23 at 09:01
  • This is an opinion based question: Which ever you are more comfortable with is the approach you should go with. Tools make it easy to do from either end as a starting point, just like tools can write tables and entities from UML if that is your preference. Production is a whole other ball game - best practice again isn't defined, but none I've seen allow a tool to generate one from the other in production. You'll want to use it as a starting point and verify the output, and use that in dev/staging/prod so that it is repeatable despite any changes or tweaks you might need to make. – Chris Jan 27 '23 at 22:52

1 Answers1

1

Both approaches work. This poll by JPA Buddy shows that 56% of developers manage their data model in the database and then synchronize DB tables with JPA entities, while 44% develop the data model as JPA entities and update the database in accordance with modifications in Java code.

So, there is no right answer to your question. If you fully control your database you can follow any path you prefer. Note, that JPA tools will fully regenerate your classes. You can use IntelliJ IDEA you can use JPA Buddy which provides a cherry-pick way to upgrade your entities.

If you follow the entity first approach, you will need to upgrade your database accordingly using some DB versioning framework like Flyway or Liquibase. Make sure you don't use auto-dll by hibernate in production as it is explained in this tutorial.

If you are given the database, you have no option other than reverse engineer tables into entities.

aleksey.stukalov
  • 706
  • 4
  • 16