advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Reviews :

Mapping Java Objects to a Database with Castor-JDO:

Handling one-to-many relations

Consider a collection of movies. Each is either in VHS or DVD format:

 

The steps to add this relation to the object model, the database model, and the Castor setup are these:

A. Java classes

The Movie class looks like this:

package hansen.playground;

import java.util.*;

public class Movie {

  private int id;
  private String title;
  private Media media;  
  
  public Movie() {};
  public Movie(int id, String title) { this.id = id; 
                                       this.title = title;};
  
  public int getId() { return id; }
  public void setId(int id) { this.id = id; }

  public String getTitle() { return title; }
  public void setTitle(String title) { this.title = title; }

  public Media getMedia() { return media; }
  public void setMedia(Media media) { this.media = media; }
  
}

- Listing 4: The Movie class -

In Media you add a Collection to keep the movies in:

private Collection movies = new ArrayList();
  
public Collection getMovies() { return movies; }
public void setMovies(Collection movies) { 
  this.movies = movies; 
}

public void addMovie(Movie movie) {
  movies.add(movie);
}

B. Database tables 

Create the movie table:

CREATE TABLE movie (
  id int NOT NULL,
  id_media int NOT NULL,
  title varchar(100),
  PRIMARY KEY (id)
) 

id_media is the foreign key to the media table. The key, id, may be generated automatically by MySQL (and many other database systems), but to keep the examples vendor neutral, I've chosen not to use this feature in this article.

C. The mappings file 

Modify the mapping.xml file: 

<class name="hansen.playground.Movie" identity="id">
  <map-to table="movie" />
  <field name="id" type="integer">
    <sql name="id" type="integer"/>
  </field>
  <field name="title" type="string">
    <sql name="title" type="varchar" />
  </field>
  <field name="media" type="hansen.playground.Media" required="true">
    <sql name="id_media" />
  </field>
</class>
<class name="hansen.playground.Media" identity="id">
  <map-to table="media" />
  <field name="id" type="integer">
    <sql name="id" type="integer"/>
  </field>
  <field name="type" type="string">
    <sql name="type" type="char" />
  </field>
  <field name="movies" type="hansen.playground.Movie" collection="collection">
    <sql many-key="id_media" />
  </field>
</class>

This is the most interesting part of the setup. The new things are these:

  • the Movie object refers to the Media object by giving the name of the class as the type.
    We want a media for every movie hence required=true.    
  • the Media object also refers to the Movie objects by giving the class name and also the kind of Java object that is used to hold the movies.
    There is no field in the media table that corresponds to movies, instead we use the many-key attribute to give Castor the name of the field that holds the foreign key in the Movie object.   

D. Test the setup

Let's assume that we have two records in the Media table:

id
type
1
DVD
2
VHS

Here's a program that creates three movies, two in DVD format, one in VHS:

package hansen.playground;
import org.exolab.castor.jdo.*;
import java.util.*;

public class CreateMovies {
  public static void main(String[] args) {
    try {
      // Define the JDO object
      JDO jdo = new JDO("mydb"); 
      jdo.setConfiguration("database.xml"); 

      // Open a connection to the database
      Database db = jdo.getDatabase();
      
      // Begin a transaction
      db.begin(); 
      // Load the DVD and VHS objects using their keys
      Media DVD = (Media)db.load(Media.class,new Integer(1));
      Media VHS = (Media)db.load(Media.class,new Integer(2));

      Movie m1 = new Movie(11, "The Matrix");
      m1.setMedia(DVD);
      DVD.addMovie(m1);
      db.create(m1);
      
      Movie m2 = new Movie(12, "Lord of the Rings");
      m2.setMedia(DVD);
      DVD.addMovie(m2);
      db.create(m2);

      Movie m3 = new Movie(13, "Chain Reaction");
      m3.setMedia(VHS);
      VHS.addMovie(m3);
      db.create(m3);

      // Commit the transaction
      db.commit(); 
      db.close(); 

    } catch (PersistenceException e) {
      e.printStackTrace(); 
    }  
  }
}

- Listing 5: Testprogram for the Movie class -

If we now look into the movie table we'll find these three records:

id
id_media
title
11
1
The Matrix
12
1
Lord of the Rings
13
2
Chain Reaction

You'll notice that the keys for the DVD media (1) and VHS (2) have been inserted in the foreign key fields.    

How to Add Java Applets to Your Site

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.

 DevX Skillbuilding from IBM developerWorks
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 48
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Apple Details iPhone/Mac Developer Event
RIM Ups Ante With Mobile Software Push
Novell Readies Silverlight Clone for Linux
Yahoo Pitches The 'Next Generation of Search'
Alfresco's Latest ECM: Prying Open a Sector?
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads for the JON 2.0
Out with the Old, in with the New at JavaOne

Create Secure Java Applications Productively, Part 1: Use Rational Application Developer and Data Studio
.NET Building Blocks: Custom User Control Fundamentals
Secure Internet File-Sharing with PHP, MySQL, and JavaScript
Getting Started with TBB on Windows
Moving to VoIP: Should You Go It Alone?
Introduction to the WPF Command Framework
7.0, Microsoft's Lucky Version?
Will Hyper-V Make VMware This Decade's Netscape?
Eliminate Fragmentation Frustration with Netbiscuits
Taming Trees: Building Branching Structures

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES