|
What just happened?
We were able to use Hibernate to create a data table in which we can
persist instances of the Java class it created for us. We
didn't have to type a single line of SQL or Java! Of
course, our table is still empty at this point.
Let's change that! The next chapter will look at the
stuff you probably most want to see: using Hibernate from within a
Java program to turn objects into database entries and vice versa.
NOTE
It's about time? Yeah, I suppose. But at least you didn't have to figure out all these steps from scratch!
Before diving into that cool task, it's worth taking
a moment to reflect on how much we've been able to
accomplish with a couple of XML and properties files. Hopefully
you're starting to see the power and convenience
that make Hibernate so exciting.
What about...
. . . Other approaches to ID generation? Keys that are globally
unique across a database or the world? Hibernate can support a
variety of methods for picking the keys for objects it stores in the
database. This is controlled using the generator
tag, line 15 in Example 2-1. In this example we told Hibernate to use the
most natural kind of keys for the type of database that it happens to
be using. Other alternatives include the popular
"hi/lo" algorithm, global UUIDs,
leaving it entirely up to your Java code, and more. See the
"generator" section in the Basic
O/R Mapping chapter of the Hibernate reference documentation for
details. And, as usual, if none of the built-in choices are perfect
for your needs, you can supply your own class to do it exactly how
you'd like, implementing the interface
net.sf.hibernate.id.IdentifierGenerator and supplying your class name in the
generator tag.
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, Section 2.3. 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.
NOTE
This example assumes you've already got a working MySQL instance installed and running, 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
fromhttp://www.mysql.com).
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
1 % mysql -u root -p
2 Enter password:
3 Welcome to the MySQL monitor. Commands end with ; or \g.
4 Your MySQL connection id is 764 to server version: 3.23.44-Max-log
5
6 Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
7
8 mysql> CREATE DATABASE notebook_db;
9 Query OK, 1 row affected (0.00 sec)
10
11 mysql> GRANT ALL ON notebook_db.* TO jim IDENTIFIED BY "s3cret";
12 Query OK, 0 rows affected (0.20 sec)
13
14 mysql> quit;
15 Bye
Make a note of the database name you create, as well as the username
and password that can access to it. These will need to be entered
into hibernate.properties, as shown in Example 2-9.
NOTE
Hopefully you'll use a less guessable password than this in your real databases!
Next, you'll need a JDBC driver capable of
connecting to MySQL. If you're already using MySQL
for your Java projects, you'll have one. Otherwise,
you can download Connector/J from http://www.mysql.com/downloads/api-jdbc-stable.html.
However you obtain it, copy the driver library jar (which will be
named something like
mysql-connector-java-3.0.10-stable-bin.jar) to
your project's lib directory
alongside the HSQLDB, Hibernate, and other libraries that are already
there. It's fine to have drivers for several
different databases available to your code; they
won't conflict with each other, since the
configuration file specifies which driver class to use.
Speaking of which, it's time to edit
hibernate.properties to use the new driver and
database we've just made available. Example 2-9 shows how it is set up to connect to my MySQL
instance using the database created in Example 2-8.
You'll need to tweak these values to correspond to
your own server, database, and the login credentials you chose. (If
you're using MM.MySQL, the older incarnation of the
MySQL JDBC driver, the driver_class will need to
be com.mysql.jdbc.Driver.)
Example 2-9. Changes to hibernate.properties to connect to the new MySQL database
1 hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
2 hibernate.connection.driver_class=com.mysql.jdbc.Driver
3 hibernate.connection.url=jdbc:mysql://slant.reseune.pvt/notebook_db
4 hibernate.connection.username=jim
5 hibernate.connection.password=s3cret
The URL on the third line will need to reflect your server; you
won't be able to resolve my private internal domain
name, let alone route to it.
Once this is all set, you can rerun the schema creation example that
was set up in the previous section. This time it will build the
schema on your MySQL server rather than in the embedded HSQLDB world.
You'll see output like that
in
Example 2-10.
Example 2-10. Schema creation when connecting to MySQL
1 % ant schema
2 Buildfile: build.xml
3
4 prepare:
5
6 compile:
7
8 schema:
9 [schemaexport] 23:02:13,614 INFO Environment:462 - Hibernate 2.1.2
10 [schemaexport] 23:02:13,659 INFO Environment:496 - loaded properties from
11 resource hibernate.properties: {hibernate.connection.username=jim, hibernate.
12 connection.password=s3cret, hibernate.cglib.use_reflection_optimizer=true,
13 hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect, hibernate.connection.
14 url=jdbc:mysql://slant.reseune.pvt/notebook_db, hibernate.connection.driver_
15 class=com.mysql.jdbc.Driver}
16 [schemaexport] 23:02:13,711 INFO Environment:519 - using CGLIB reflection
17 optimizer
18 [schemaexport] 23:02:13,819 INFO Configuration:166 - Mapping file: /Users/jim/
19 Documents/Work/OReilly/Hibernate/Examples/ch02/classes/com/oreilly/hh/Track.hbm.xml
20 [schemaexport] 23:02:15,568 INFO Binder:229 - Mapping class: com.oreilly.hh.
21 Track -> TRACK
22 [schemaexport] 23:02:16,164 INFO Dialect:82 - Using dialect: net.sf.hibernate.
23 dialect.MySQLDialect
24 [schemaexport] 23:02:16,175 INFO Configuration:595 - processing one-to-many
25 association mappings
26 [schemaexport] 23:02:16,188 INFO Configuration:604 - processing one-to-one
27 association property references
28 [schemaexport] 23:02:16,209 INFO Configuration:629 - processing foreign key
29 constraints
30 [schemaexport] 23:02:16,429 INFO Configuration:595 - processing one-to-many
31 association mappings
32 [schemaexport] 23:02:16,436 INFO Configuration:604 - processing one-to-one
33 association property references
34 [schemaexport] 23:02:16,440 INFO Configuration:629 - processing foreign key
35 constraints
36 [schemaexport] 23:02:16,470 INFO SchemaExport:98 - Running hbm2ddl schema export
37 [schemaexport] 23:02:16,488 INFO SchemaExport:117 - exporting generated schema
38 to database
39 [schemaexport] 23:02:16,543 INFO DriverManagerConnectionProvider:41 - Using
40 Hibernate built-in connection pool (not for production use!)
41 [schemaexport] 23:02:16,549 INFO DriverManagerConnectionProvider:42 - Hibernate
42 connection pool size: 20
43 [schemaexport] 23:02:16,583 INFO DriverManagerConnectionProvider:71 - using
44 driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://slant.reseune.pvt/notebook_db
45 [schemaexport] 23:02:16,597 INFO DriverManagerConnectionProvider:72 - connection
46 properties: {user=jim, password=s3cret}
47 [schemaexport] drop table if exists TRACK
48 [schemaexport] 23:02:18,129 DEBUG SchemaExport:132 - drop table if exists TRACK
49 [schemaexport] create table TRACK (
50 [schemaexport] TRACK_ID INTEGER NOT NULL AUTO_INCREMENT,
51 [schemaexport] title VARCHAR(255) not null,
52 [schemaexport] filePath VARCHAR(255) not null,
53 [schemaexport] playTime TIME,
54 [schemaexport] added DATE,
55 [schemaexport] volume SMALLINT,
56 [schemaexport] primary key (Track_id)
57 [schemaexport] )
58 [schemaexport] 23:02:18,181 DEBUG SchemaExport:149 - create table TRACK (
59 [schemaexport] TRACK_ID INTEGER NOT NULL AUTO_INCREMENT,
60 [schemaexport] title VARCHAR(255) not null,
61 [schemaexport] filePath VARCHAR(255) not null,
62 [schemaexport] playTime TIME,
63 [schemaexport] added DATE,
64 [schemaexport] volume SMALLINT,
65 [schemaexport] primary key (Track_id)
66 [schemaexport] )
67 [schemaexport] 23:02:18,311 INFO SchemaExport:160 - schema export complete
68 [schemaexport] 23:02:18,374 INFO DriverManagerConnectionProvider:137 - cleaning
69 up connection pool: jdbc:mysql://slant.reseune.pvt/notebook_db
70
71 BUILD SUCCESSFUL
72 Total time: 9 seconds
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|