Commit 985b5e0c authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
9780596528188
\ No newline at end of file
<?xml version="1.0"?>
<project name="Getting Started with Hibernate 3"
default="db" basedir=".">
<!-- Set up properties containing important project directories -->
<property name="source.root" value="src"/>
<property name="class.root" value="classes"/>
<property name="lib.dir" value="lib"/>
<property name="data.dir" value="data"/>
<!-- Set up the class path for compilation and execution -->
<path id="project.class.path">
<!-- Include our own classes, of course -->
<pathelement location="${class.root}" />
<!-- Include jars in the project library directory -->
<fileset dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="db" description="Runs HSQLDB database management UI
against the database file--use when application is not running">
<java classname="org.hsqldb.util.DatabaseManager"
fork="yes">
<classpath refid="project.class.path"/>
<arg value="-driver"/>
<arg value="org.hsqldb.jdbcDriver"/>
<arg value="-url"/>
<arg value="jdbc:hsqldb:${data.dir}/music"/>
<arg value="-user"/>
<arg value="sa"/>
</java>
</target>
<!-- Set up the class path for the Hibernate Tools -->
<path id="tool.class.path">
<!-- Include our own classes, mostly for logging configuration -->
<pathelement location="${class.root}" />
<!-- Include all jars in the tool directory and subdirectories -->
<fileset dir="tools">
<include name="**/*.jar"/>
</fileset>
</path>
<!-- Teach Ant how to use the Hibernate Tools -->
<taskdef name="hibernatetool"
classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="tool.class.path"/>
<!-- Generate the java code for all mapping files in our source tree -->
<target name="codegen" depends="prepare"
description="Generate Java source from the O/R mapping files">
<hibernatetool destdir="${source.root}">
<configuration>
<fileset dir="${source.root}">
<include name="**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2java/>
</hibernatetool>
</target>
<!-- Create our runtime subdirectories and copy resources into them -->
<target name="prepare" description="Sets up build structures">
<mkdir dir="${class.root}"/>
<!-- Copy our property files and O/R mappings for use at runtime -->
<copy todir="${class.root}" >
<fileset dir="${source.root}" >
<include name="**/*.properties"/>
<include name="**/*.hbm.xml"/>
</fileset>
</copy>
</target>
<!-- Generate the schemas for all mapping files in our class tree -->
<target name="schema" depends="compile"
description="Generate DB schema from the O/R mapping files">
<hibernatetool destdir="${source.root}">
<configuration>
<fileset dir="${class.root}">
<include name="**/*.hbm.xml"/>
</fileset>
</configuration>
<hbm2ddl drop="yes" />
</hibernatetool>
</target>
<!-- Compile the java source of the project -->
<target name="compile" depends="prepare"
description="Compiles all Java classes">
<javac srcdir="${source.root}"
destdir="${class.root}"
debug="on"
optimize="off"
deprecation="on">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="ctest" description="Creates and persists some sample data"
depends="compile">
<java classname="com.oreilly.hh.CreateTest" fork="true">
<classpath refid="project.class.path"/>
</java>
</target>
<target name="qtest" description="Run a simple Hibernate query"
depends="compile">
<java classname="com.oreilly.hh.QueryTest" fork="true">
<classpath refid="project.class.path"/>
</java>
</target>
</project>
package com.oreilly.hh;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.sql.Time;
import java.util.Date;
/**
* Create sample data, letting Hibernate persist it for us.
*/
public class CreateTest {
public static void main(String args[]) throws Exception {
// Create a configuration based on the properties file we've put
// in the standard place.
Configuration config = new Configuration();
// Tell it about the classes we want mapped, taking advantage of
// the way we've named their mapping documents.
config.addClass(Track.class);
// Get the session factory we can use for persistence
SessionFactory sessionFactory = config.buildSessionFactory();
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
// Create some data and persist it
tx = session.beginTransaction();
Track track = new Track("Russian Trance",
"vol2/album610/track02.mp3",
Time.valueOf("00:03:30"), new Date(),
(short)0);
session.save(track);
track = new Track("Video Killed the Radio Star",
"vol2/album611/track12.mp3",
Time.valueOf("00:03:49"), new Date(),
(short)0);
session.save(track);
track = new Track("Gravity's Angel",
"vol2/album175/track03.mp3",
Time.valueOf("00:06:06"), new Date(),
(short)0);
session.save(track);
// We're done; make our changes permanent
tx.commit();
} catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
// Clean up after ourselves
sessionFactory.close();
}
}
package com.oreilly.hh;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.sql.Time;
import java.util.*;
/**
* Retrieve data as objects
*/
public class QueryTest {
/**
* Retrieve any tracks that fit in the specified amount of time.
*
* @param length the maximum playing time for tracks to be returned.
* @param session the Hibernate session that can retrieve data.
* @return a list of {@link Track}s meeting the length restriction.
* @throws HibernateException if there is a problem.
*/
public static List tracksNoLongerThan(Time length, Session session)
throws HibernateException
{
Query query = session.getNamedQuery(
"com.oreilly.hh.tracksNoLongerThan");
query.setTime("length", length);
return query.list();
}
/**
* Look up and print some tracks when invoked from the command line.
*/
public static void main(String args[]) throws Exception {
// Create a configuration based on the properties file we've put
// in the standard place.
Configuration config = new Configuration();
// Tell it about the classes we want mapped, taking advantage of
// the way we've named their mapping documents.
config.addClass(Track.class);
// Get the session factory we can use for persistence
SessionFactory sessionFactory = config.buildSessionFactory();
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
try {
// Print the tracks that will fit in five minutes
List tracks = tracksNoLongerThan(Time.valueOf("00:05:00"),
session);
for (ListIterator iter = tracks.listIterator() ;
iter.hasNext() ; ) {
Track aTrack = (Track)iter.next();
System.out.println("Track: \"" + aTrack.getTitle() +
"\", " + aTrack.getPlayTime());
}
} finally {
// No matter what, close the session
session.close();
}
// Clean up after ourselves
sessionFactory.close();
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.oreilly.hh.Track" table="TRACK">
<meta attribute="class-description">
Represents a single playable track in the music database.
@author Jim Elliott (with help from Hibernate)
</meta>
<id name="id" type="int" column="TRACK_ID">
<meta attribute="scope-set">protected</meta>
<generator class="native"/>
</id>
<property name="title" type="string" not-null="true"/>
<property name="filePath" type="string" not-null="true"/>
<property name="playTime" type="time">
<meta attribute="field-description">Playing time</meta>
</property>
<property name="added" type="date">
<meta attribute="field-description">When the track was created</meta>
</property>
<property name="volume" type="short" not-null="true">
<meta attribute="field-description">How loud to play the track</meta>
</property>
</class>
<query name="com.oreilly.hh.tracksNoLongerThan">
<![CDATA[
from com.oreilly.hh.Track as track
where track.playTime <= :length
]]>
</query>
</hibernate-mapping>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:data/music
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.shutdown=true
hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:data/music
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.shutdown=true
hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://slant.reseune.pvt/notebook_db
hibernate.connection.username=jim
hibernate.connection.password=s3cret
hibernate.connection.shutdown=true
hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=warn
### log just the SQL
#log4j.logger.net.sf.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.net.sf.hibernate.type=info
### log schema export/update ###
log4j.logger.net.sf.hibernate.tool.hbm2ddl=debug
### log cache activity ###
#log4j.logger.net.sf.hibernate.cache=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace
## Example files for the title:
# Getting Started with Hibernate 3, by James Elliott
[![Getting Started with Hibernate 3, by James Elliott](http://akamaicovers.oreilly.com/images/9780596528188/cat.gif)](https://www.safaribooksonline.com/library/view/title/0596528183//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment