questzen
questzen

Reputation: 3287

How to generate 'java code with annotations' from emf model

More precisely, I want to know, how one can model annotations into the ecore model definition. So that the generated java code would contain them. (For eg: hibernate persistence tags)

Upvotes: 6

Views: 2069

Answers (2)

Arcanefoam
Arcanefoam

Reputation: 717

This post on the EMF Forums discusses how to use custom templates for code generation: https://www.eclipse.org/forums/index.php/t/131673/.

In a nutshell, you can dynamically provide different templates for your code generation, making it possible to insert the required annotations. In the forum post, Ed Merks (the EMF lead) suggests two pieces of information to read:

and a small example of how to use them:

The inserts look like this:

<%@ include file="Class/getGenFeature.annotations.insert.javajetinc" fail="silent" %>

so under your templates folder you'd create files like this:

<someproject>/templates/model/Class/getGenFeature.annotations.insert.java jetinc

and whatever you put in the file will be inserted on the getter. Likely you'd include guards like this:

<%if (isImplementation) {%>
@Something
<%}%>

Try to follow the convention of using tabs for the indentation since these will be converted to the formatting preference of the target project.

Once you can provide your own templates you have two choices:

  1. Add the hibernate tags by default to all your code
  2. Modify the templates to read annotations in the ecore model.

For 2, you will need to define your own annotation source (basically a url), something like https://myproject/emf/hibernate and then add EAnnotations to your EClasses that use your custom url and provide key:value settings (e.g. the hibernate annotation to add). Your custom template can then read the annotations from the EClass, query if your source is used and then used the provided values to add the Java annotations.

The post also mentions the Teneo project, that provides JPA support for EMF. No recent development has been done (apparently), but it can be mature enough to use.

Upvotes: 1

Diego Sevilla
Diego Sevilla

Reputation: 29001

I don't think you can to this out of the box. However, you could look into the parameters of the ".genmodel" file to see if you can tweak how annotations (EAnnotations) are being output to the files. The problem with code generation templates is that they are fixed, but maybe through some option in the genmodel you can control how annotations get written to files.

Upvotes: 0

Related Questions