This tutorial assumes that you have followed these other tutorials in the specified order:

  1. Eclipse EMF: Designing the Model
  2. Eclipse EMF: a CRUD at no-cost

the goal here is to show how, with just some extra lines of code added to the EMF generated plugins, we can have our model persisted and maintained on a database.
We will use MySQL as the target database, so make sure you have the access to such a database server (you can always download it at http://www.mysql.com/downloads/mysql). We’ll use the “test” schema (pre-loaded empty while installing MySQL); anyway you can use another schema simply by changing the connection properties (ahead in this tutorial).

In order to follow the next steps we’ll need some additional plugins for Eclipse. Here you can find details on how to install them

Teneo Setup for Eclipse 4.2 ÔÇô Juno

Let’s start from the end of the previous tutorial and open file plugin.xml of the editor plugin which was generated automatically by EMF
(it.rcpvision.rcptutorial.model.editor).

Open tab Dependencies

and add the following plugins among Dependences (press button Add… in section Required Plug-ins):

  • org.eclipse.emf.teneo.hibernate
  • org.hibernate
  • com.mysql.jdbc

save (Ctrl-S) and open class LibraryEditorAdvisor.java, in particular the method initialize().

and proceed with the following changes:

first of all let’s mark the method as @generated not; this way, when a new generation will take place (let’s say for a model evolution), our code change will not be overwritten.

now let’s add the following source code after the instruction

configurer.setSaveAndRestore(true);

		//*************** Initialize Teneo Hibernate DataStore *************************************
		HbDataStore hbds = (HbDataStore) HbHelper.INSTANCE.createRegisterDataStore("MyDb");
		//Set Database properties
		Properties props = new Properties();
		props.setProperty(Environment.DRIVER, "com.mysql.jdbc.Driver");
		props.setProperty(Environment.URL, "jdbc:mysql://localhost:3306/test");
		props.setProperty(Environment.USER, "root");
		props.setProperty(Environment.PASS, "admin");
		props.setProperty(Environment.DIALECT,	org.hibernate.dialect.MySQL5Dialect.class.getName());
		props.setProperty(Environment.SHOW_SQL, "true");
		props.setProperty(Environment.HBM2DDL_AUTO, "update");
		// props.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
		hbds.setDataStoreProperties(props);
		//Register EMF package
		hbds.setEPackages(new EPackage[] { LibraryPackage.eINSTANCE });
		hbds.initialize();

		//*************** Initialize Database Content Data *************************************
		// (the first time a new Library object container is persisted, otherwise it is loaded)
		String uriStr = "hibernate://?"+HibernateResource.DS_NAME_PARAM+"=MyDb";
		final URI uri = URI.createURI(uriStr);
		ResourceSet resourceSet = new ResourceSetImpl();
		Resource resource = resourceSet.createResource(uri);
		try {
			resource.load(null);
			if (resource.getContents().size() == 0) {
				resource.getContents().add(LibraryFactory.eINSTANCE.createLibrary());
				resource.save(null);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//*************** Open an Editor instance *************************************
		//(avoiding the need of some "File, New..." explicit user operation)
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				try {
					PlatformUI
							.getWorkbench()
							.getActiveWorkbenchWindow()
							.getActivePage()
							.openEditor(new URIEditorInput(uri),
									"library.presentation.LibraryEditorID");
				} catch (PartInitException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});

The needed imports are:

 

import java.util.Properties;
import java.io.IOException;
import library.LibraryFactory;
import library.LibraryPackage;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.teneo.hibernate.HbDataStore;
import org.eclipse.emf.teneo.hibernate.HbHelper;
import org.eclipse.emf.teneo.hibernate.resource.HibernateResource;
import org.hibernate.cfg.Environment;

We will not get into the details of the code above (this will be explained in other articles), but here is a quick description:

  • the Teneo Hibernate DataStore is being initializated, giving the database coordinates (URL, credentials, type, etc…). This is the point where you could consider changing parameter Environment.URL in order to match your schema name (“test” in this article), as well as making sure the credentials (USER e PASS) for the database access are correct.
    When parameter HBM2DDL_AUTO is set to “update“, it allows the database to “adapt” (when possible, with proper ALTER TABLE automatic statements) to the model evolution. A “create-drop” value will instead lead to a fresh and empty new database at every launch (this may seem a useless option at first, but it becomes very useful when testing, where starting every time from scratch is a key point)
  • a connection is made to a ResourceSet (a pure EMF concept, independent from the specific implementation choice for the persistence) on the DataStore. This is required in order to assure that there is one Library object persisted, that will act as a container for the data we will manage afterwards.
    Then we load the resources, through resource.load(null), and verify that a Library object exists; if not (e.g. the first time) we create it and save.
  • an Editor (just the one generated from EMF for our model) is opened, fed with a URI input that refers to the created DataStore.

That’s all! Let’s just launch the application.

Note: you should already have the right launch in Run
-> Run History
-> it.rcpvision.rcptutorial.model.editor.LibraryEditorAdvisorApplication
from last tutorial.

However you can always launch it from the Editor project plugin.xml, tab Overview, hyperlink Launch an Eclipse Application.

 

If the launch is correct (otherwise do a Clean and Launch checking) you should see (just the first time, when the Library object is created) the following messages on the console

this means that the initial insert of the Library object has been performed successfully.

The application should show like this:

now you can start filling the Library with Author e Book objects, linked toghether, as in the previous tutorial Eclipse EMF: a CRUD at no-cost.
This time however, data will be made persistent on the database (instead that on a XMI file). You can verify this on the console and obviously on the database!

Next time we will see how to quickly develop EMF-based RCP applications using the visual designer WindowBuilder.

Back to index