Connecting Hibernate to MySQL
Of course, as nifty and self-contained as HSQLDB may be, 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).
This example assumes you've already got a working MySQL instance, and can administer it.
To highlight this flexibility, let’s take a look at what we’d change in our schema-creation example if we wanted to connect Hibernate to a MySQL database.
Connect to your MySQL server and set up a new database to play with, as shown in Example 20.
Example 20. 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.06 sec) mysql> GRANT ALL ON notebook_db.* TO jim IDENTIFIED BY "s3cret"; Query OK, 0 rows affected (0.07 sec) mysql> quit; Bye
Make a note of the database name you create, as well as the user and password that you grant access to it. These will need to be entered into hibernate.properties, as shown in Example 21. (And hopefully you’ll use a more robust password than this in your real databases!)
Next, you’ll need a JDBC driver capable of connecting ...