HomeEMF HibernateEMF JDO/JPOXWeb App GenerationServices
 

Step 3: Retrieve and add EMF Objects

In this part of the tutorial we retrieve the Library from the database back-end and perform some checks on and additions to the existing data.

Retrieve Library Object

Obtain the Library we created in the previous step from the database:

final Session session = sessionFactory.openSession();
session.beginTransaction();

// Retrieve the Library and its child objects.
// Note that you can use the EClass name in the query.
Query query = session.createQuery("FROM Library");			
List libraries = query.list();
Library library = (Library) libraries.get(0);

As noted in the source, you must use the EClass name in the query. (In most cases it's identical to the Java class name).

Perform some checks

Now that we have a Library object, we obtain a few of its child objects and verify that we have the correct information.

// Obtain the Writer and Book
Writer writer = (Writer) library.getWriters().get(0);
System.out.println(writer.getName());
Book book = (Book) library.getBooks().get(0);
System.out.println(book.getTitle());

// Verify that the eContainer and references are set correctly. 
assert (book.eContainer() == library);
assert (writer.getBooks().get(0) == book);

As expected, the objects retrieved from the database store comply to the ECore API. (EObject.eClass(), EObject.eContainer(), etc.)

Add a new Book and Writer

Now we add a new Book and Writer to the library:

// Add a new Writer and Book
Writer georgeOrwell = LibraryFactory.eINSTANCE.createWriter();
georgeOrwell.setName("G. Orwell");

// Create a new Book and set the Writer and Library.
Book georgesBook = LibraryFactory.eINSTANCE.createBook();
georgesBook.setPages(250);
georgesBook.setTitle("1984");
georgesBook.setCategory(BookCategory.SCIENCE_FICTION);
georgesBook.setAuthor(georgeOrwell);

library.getBooks().add(georgesBook);
library.getWriters().add(georgeOrwell);

// Commit.
session.getTransaction().commit();
session.close();

Next Step

The next step of the tutorial shows some Hibernate HQL queries retrieving EMF objects from the database.

Click here to go to the next step.