HomeEMF HibernateEMF JDO/JPOXWeb App GenerationServices
 

Step 5: Using Hibernate EMF Resources

The EMF Resource concept is very different from a relational/querying approach. In this part of the tutorial it is described how objects can be loaded, updated and saved using the Hibernate EMF resource implementation.

For more information on Hibernate EMF resource see.

Create a resource

An EMF resource is retrieved using a specific URL. An example of a URL which retrieves a hibernate resource is: hibernate://?dsname=MySF. The first (protocol) part of this URL should be hibernate. The rest of the URL in this example consists of one parameter, nl. dsname. The dsname parameter (or better the constant HibernateResource.DS_NAME_PARAM) should be set to the name of the SessionFactory created through the HibernateHelper.INSTANCE.createRegisterSessionFactory call. See step 2 of this tutorial.

String uriStr = "hibernate://?" + HibernateResource.DS_NAME_PARAM + "=MySF";
final URI uri = URI.createURI(uriStr);
ResourceSet resourceSet = new ResourceSetImpl();
final Resource res = resourceSet.createResource(uri);
	

Load the resource

The resource can now be loaded. In this example we also get the contents and iterate throught them.

res.load(Collections.EMPTY_MAP);
Iterator it = res.getContents().iterator();
Library libTest;
while (it.hasNext())
{
	libTest = (Library)it.next();
	System.out.println(libTest.getName());
}

The above makes clear that only the Library objects are present as a top level object. The other objects can always be reached from the library objects. See here for a discussion of this characteristic.

Update and add

Now a new library, writer and book are added to the library example.

Library libNew = LibraryFactory.eINSTANCE.createLibrary();
libNew.setName("My Second Library");
	
// create a writer
Writer writerNew = LibraryFactory.eINSTANCE.createWriter();
writerNew.setName("I. Asimov");
   
// and one of his books
Book bookNew = LibraryFactory.eINSTANCE.createBook();
bookNew.setAuthor(writerNew);
bookNew.setPages(305);
bookNew.setTitle("Foundation and Empire");
bookNew.setCategory(BookCategory.SCIENCE_FICTION);

// add the writer/book to the library.
libNew.getWriters().add(writerNew);
libNew.getBooks().add(bookNew);
	
// now add the top-level object to the resource
res.getContents().add(libNew);

Because the new library object is added to the resource also its children (the book and writer) are added to the resource.

Save the resource

Now save the resource. Note that the resource handles things like transactions.

res.save(Collections.EMPTY_MAP);