Step 5: Using EMF/JPOX 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 EMF JPOX resource implementations (the org.eclipse.emf.teneo.jpox.resource.JPOXResource.
For more information on the EMF JPOX resource see.
Create a resource
An EMF resource is retrieved using a specific URL. The protocol of the URI is jpox. In addition the URI has to contain the JPOXResource.DS_NAME_PARAM parameter. This parameter should be set to the name of the JpoxDataStore created through the JpoxHelper.INSTANCE.createRegisterDataStore call. See step 2 of this tutorial.
String uriStr = "jpox://?" + JPOXResource.DS_NAME_PARAM + "=MyPMF"; 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
The following code adds a new library, writer and book.
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); // 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
Save the resource. The JPOXResource handles things like transactions.
res.save(Collections.EMPTY_MAP);