2.4. Connecting Hibernate to MySQL

If you were skimming through this chapter (or, more likely, the table of contents) you may not have even noticed that Hibernate connected to and manipulated a database in the previous section, "Cooking Up a Schema." Since working with databases is the whole point of Hibernate, it makes this as easy as possible. Once you've set up a configuration file like the one in Example 2-4, the schema generation tool can get in and work with your database, and your Java code can use it for persistence sessions as demonstrated in Chapter 3.

This example assumes you've already got a working MySQL instance installed andrunning, since explaining how to do that would be quite a detour.

In the interest of further clarifying this aspect of working with Hibernate, let's take a look at what we'd change in that example to set up a connection with the popular, free, and open source MySQL database (available from http://www.mysql.com).

2.3.1. How do I do that?

Connect to your MySQL server and set up a new database to play with, along the lines of Example 2-8.

Example 2-8. Setting up the MySQL database notebook_db as a Hibernate playground
% mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 764 to server version: 3.23.44-Max-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> CREATE DATABASE notebook_db;
Query OK, 1 row affected (0.00 sec)

mysql> GRANT ALL ON notebook_db.* TO jim IDENTIFIED ...

Get Hibernate: A Developer's Notebook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.