I am curious, what ways there are, to fill database-tables using hibernate.
I am a Java EE beginner and only know two ways:
- Creating an instance of a class and persisting it via EntityManager.
- Using import.sql.
If there are many other ways, please mention the benefits of using them.
Thank you in advance!
You've pretty much covered the two main methods used, so I'll give you the pro's and cons of each.
Method 1: Getting Hibernate to generate SQL to create tables based on Object Definitions:
Pros
- Easy to do, write your objects and Hibernate will do the rest.
- You can get the exact SQL that Hibernate used by pretty-printing the SQL to your logs.
- Can be used to easily set up your relations between objects in the database.
- Great for getting a project's backend set up quickly or generating a database to unit test from.
- Hibernate can even generate out things like ID sequences.
- Hibernate can automatically clean up your schema when you close the application.
Cons
- If your relations are logically incorrect, Hibernate won't care, it will just create the mapping you gave it.
- Can't realistically be used in a production environment because you have no control over what Hibernate will generate out. If you made a mistake in your object's, it will instantly change your database. DBA's will be after your blood.
Method 2: Generating your schema with written SQL:
Pros
- You have a lot more control over your schema, and you know exactly what is getting generated where.
- You can reverse engineer your objects to match an SQL schema quite easily once you are confidant that your SQL schema is correct, because Hibernate will tell you exactly what object is violating what condition.
- Safe to use in production because you can give your scripts to a DBA and ask them to ensure the production database matches the schema.
- Good for when you have a schema you know works and you need objects that match your tables.
- Also good for when you are creating a system where you don't have control over the database.
Cons
- Pain to get right first time. Its an exercise in trial and error.
- Have to clean up after yourself by writing destroy scripts.
- Have to remember to refactor the SQL when you refactor the objects that the tables represent.
- You have to perform null checks on your objects using Javax Validation annotations or be prepared to catch a whole pile of
ConstraintViolationException
's.
- Hibernate will tell you what condition an object is violating, but it will be some obscure non-meaningful constraint name.
I hope that's given you some idea of how these can be used and in what circumstances. If anyone feels I've missed things out, feel free to comment.