Chapter 10. Connecting Hibernate to MySQL

Setting Up a MySQL Database

As nifty and self-contained as HSQLDB is, your project may not be in the market for an embedded Java database. In fact, you’re likely going to want to interface with some existing, external database server. Luckily, that’s just as easy (assuming you have the database already up and running, which is certainly beyond the scope of this walkthrough).

Note

This example assumes you’ve already got a working MySQL instance, and can administer it.

To highlight this flexibility in database choices, let’s take a look at what we’d change in Chapter 2 if we wanted to connect Hibernate to a MySQL database.

How do I do that?

Connect to your MySQL server and set up a new database to play with, as shown in Example 10-1.

Example 10-1. Setting up the MySQL database notebook_db
% mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 5.0.21

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

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

mysql> GRANT ALL ON notebook_db.* TO 'jim'@'janus.reseune.pvt' IDENTIFIED BY 's3
cret';
Query OK, 0 rows affected (0.02 sec)

mysql> quit;
Bye

Make a note of the database name you create, as well as the user and password that grant access to it. You will need to enter these into hibernate.cfg.xml, as shown later in Example 10-3. (And hopefully you’ll use a more robust password than this in ...

Get Harnessing Hibernate now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.