How To Create A Hibernate Project in Maven

In this post, I will be showing you how to create a Hibernate project using Maven and how we can add MySQL dependencies to it.

Here, is a whole process picture which you can click and follow the steps. The direction of the process has been indicated by arrow icons.



Now, configuring the Hibernate XML file:

  • Inside your project folder, right-click on 'src/main/java' and select New > Other... > Type filter text: xml > Under XML folder, click on XML File > Click Next > Under File Name, type: hibernate.cfg.xml > Finish.
  • Inside this hibernate.cfg.xml file, we would now need a dtd line. dtd stands for 'document type definition'. It defines the tagging structure of an XML document. For this, search on Google or any search engine: hibernate dtd. Find for the result that says "Index of /dtd - Hibernate". Click the link or go to https://hibernate.org/dtd/ .
  • On the next page, click on either of these three links. A dtd file will be downloaded. Open the file in any text editor. I have downloaded 'hibernate-configuration-3.0.dtd' file.


  • In the downloaded .dtd file, copy the selected text only.
  • Paste the copied line in hibernate.cfg.xml at line #2.
  • Now type the following code in hibernate.cfg.xml after line #2:


Properties:
  • connection.driver_class: This represents the class needed for MySQL connection.
  • connection.url: This represents the URL of our MySQL database which is at jdbc:mysql://localhost:3306/mydb
  • connection.username: As the name suggests, this represents the username of our database server. E.g. root
  • connection.password: Same as above, this represents the password of our database server. Eg. root
  • dialect: This represents the language or भाषा. In this case, we are using the dialect of MySQL so that Hibernate is able to communicate with MySQL in its dialect. It is dependent on which database you are using. It is different for every other database.
  • hbm2ddl.auto: This is used to create or update table by hibernate from whichever class it is mapped to. "create" will create a new table every time you run the program while "update" will only create the table if there exists no table with that name but if there is it will update the existing table.
  • show_sql: It will display which SQL query is being used by the hibernate in the console.
  • mapping: Here you will specify which class you want to map. This will include any class that will act as entity or table. Make sure to give full and proper name including the path if it resides in any package.
Now, open MySQL client, create a new database as "create database sumitkp". Type "use sumitkp" to start using that database. You can name your database anything you want!

Tip: Press CTRL + SHIFT + F on your keyboard to format your code with proper indentation if you are using Eclipse IDE.

Comments

Popular

How To Create MySQL Table with SequelizeJS

How To Read CSV Files in Java as Maven Project