/**
Author: willpower
Source: rifoo Technology (http://www.rifoo.com)
Date: 2006-07
Remarks: Reprinted please keep the above statement
**/
This section describes how to run the message of the day sample program through an instance.
After Hibernate and the database have been installed and the configuration file has been created, we need to create a class. Next, let's take a full look at all the content of these classes (the first chapter ignores a lot of details about these classes for a brief introduction ):
Listing 3-5. motd pojo class
Code:Public class motd {
Protected motd (){
}
Public motd (int id, string message ){
This. ID = ID;
This. Message = message;
}
Public int GETID (){
Return ID;
}
Public String getmessage (){
Return message;
}
Public void setid (int id ){
This. ID = ID;
}
Public void setmessage (string message ){
This. Message = message;
}
Private int ID;
Private string message;
} [Copy to clipboard]
Next, we create a custom exception class motdexception, which extends the exception class and serves as a container for all exceptions thrown by the persistence layer.
Listing 3-6. motdexception classCode:Public class motdexception extends exception {
Public motdexception (string message ){
Super (Message );
}
Public motdexception (string message, throwable cause ){
Super (message, cause );
} [Copy to clipboard]
}
Finally, let's take a look at the core code of this application:
Listing 3-7.motd ApplicationCode:Import java. util. Logging. level;
Import java. util. Logging. Logger;
Import org. hibernate. hibernateexception;
Import org. hibernate. Session;
Import org. hibernate. sessionfactory;
Import org. hibernate. transaction;
Import org. hibernate. cfg. configuration;
Public class hibernatemotd {
Public static void main (string [] ARGs ){
If (ARGs. length! = 1 ){
System. Err. println ("Nope, enter one message number ");
} Else {
Try {
Int messageid = integer. parseint (ARGs [0]);
Motd = getmotd (messageid );
If (motd! = NULL ){
System. Out. println (motd. getmessage ());
} Else {
System. Out. println ("No such message ");
}
} Catch (numberformatexception e ){
System. Err. println ("You must enter an integer-" + ARGs [0]
+ "Won't do .");
} Catch (motdexception e ){
System. Err. println ("couldn't get the message:" + E );
}
}
}
Public static motd getmotd (INT messageid)
Throws motdexception
{
Sessionfactory sessions =
New configuration (). Configure (). buildsessionfactory ();
Session session = sessions. opensession ();
Transaction Tx = NULL;
Try {
Tx = session. begintransaction ();
Motd = (motd) Session. Get (motd. Class, new INTEGER (messageid ));
TX. Commit ();
Tx = NULL;
Return motd;
} Catch (hibernateexception e ){
If (TX! = NULL) Tx. rollback ();
Log. Log (level. Severe, "cocould not acquire message", e );
Throw new motdexception (
"Failed to retrieve message from the database.", e );
} Finally {
Session. Close ();
}
}
Private Static final logger log = logger. getanonymouslogger ();
} [Copy to clipboard]
To automatically build and package these classes into a jar file, we compile an ant build. xml file:
Listing 3-8. motd ant build scriptCode:<Project default = "all">
<Property name = "hibernate" location = "/home/hibernate-3.0"/>
<Property name = "JDBC" location = "/home/HSQLDB/lib/HSQLDB. Jar"/>
<Property name = "src" location = "."/>
<Property name = "Config" location = "."/>
<Property name = "bin" location = "bin"/>
<Property name = "name" value = "motd"/>
<Path id = "classpath. Base">
<Pathelement location = "$ {bin}"/>
<Pathelement location = "$ {hibernate}/hibernate3.jar"/>
<Fileset dir = "$ {hibernate}/lib" includes = "**/*. Jar"/>
<Pathelement location = "$ {JDBC}"/>
</Path>
<Path id = "classpath. Run">
<Pathelement location = "$ {config}"/>
<Path refID = "classpath. Base"/>
</Path>
<Target name = "init">
<Mkdir dir = "$ {bin}"/>
</Target>
<Target name = "compile" depends = "init">
<Javac srcdir = "$ {SRC}" destdir = "$ {bin}">
<Classpath refID = "classpath. Base"/>
</Javac>
</Target>
<Target name = "Dist">
<Jar destfile = "$ {name}. Jar"
Basedir = "$ {bin }"
/>
</Target>
<Target name = "clean">
<Delete dir = "$ {bin}"/>
<Delete file = "$ {name}. Jar"/>
</Target>
<Target name = "all" depends = "Dist"/>
</Project> [copy to clipboard]
Run ant to generate a jar package for the message of the day application and name it motd. jar.
The next step is to create a database, which can be done manually. Of course, generating an SQL statement to create a database helps to check whether the ing file and data model are correctly matched.
To improve readability, we can set the classpath environment variable for the example, either in the window, through the-classpath parameter, or by adding a task in the ant script.
Classpath should include: hibernate3.jar
There are also the following support packages:
Commons-logging-1.0.4.jar
Cglib-full-2.0.2.jar
Commons-collections-2.1.1.jar
Antlr-2.7.4.jar
Dom4j-1.5.2.jar
Ehcache-1.1.jar
JTA. Jar
The JDBC driver package also needs to be included. HSQLDB. jar is used in this example.
The command to build schma is as follows:
Java org. hibernate. tool. hbm2ddl. schemaexport -- text -- output = motd. SQL
-- Config = hibernate. cfg. xml
The SQL statement is written to the motd. SQL file. In this way, we can use this file to create a database. At this time, we can run the application, but there is no data in the database.
Run: Java hibernatemotd 1
Return: no such message
Now we manually insert a piece of data to the database and use the script
Insert into motd (ID, message) values (1, 'Hello World ')
Run Java hibernatemotd 1 again.
Return Value: Hello World
To sum up, running this example involves three steps:
1. Create a hibernate configuration file
2. Create a Mapping File
3. Compile the pojo class