Despite using Eclipse for several years now, I’ve only recently started to use a really cool feature - templates. It may seem a bit silly at first, but it has been a very useful feature for us. Why?

- Saves a small amount of typing - it adds up though
- It helps cut down typos or forgetting how to do some of the more complicated things we do
- It helps us to use and enforce naming and coding conventions

One area where I’ve found this to be useful is in JPA mappings. People tend to forget the annotations and annotation parameters to use, get mixed up on naming conventions, and forget which data types to use in certain scenarios. In this trivial example, I want to make it so people can easily map an Id column, and I want to make sure they make it an Integer and name it ‘id’. Here is how I’ll do it.

To create a template, go to Window -> Preferences, and then to Java -> Editor -> Templates (You can also make XML and other templates in their respective areas).

Next, click the ‘New’ button and start making your template. Give it a name that is easy to remember (in this case, I am making a JPA Id Column mapping template, so I’ll call it jpaIdColumn). Fill in the template itself with the code you want to add. To add a variable (ie, something the user fills in themselves), use ${variable_name}. If you insert the same variable name in multiple places, the user will only have to type it once - Eclipse will automatically fill in the other places. Pretty cool, eh?

Click ‘OK’ and you are ready to use it. Just start typing the name to get it to pop up in the auto-complete list (ie, jpa…)

When you select it in the auto-complete menu, it will fill in the code and select the first variable to replace:

You can type or paste in the text you want in there. If there were more than one variable to replace, you would easily move through them using the TAB key. The only pitfall? Don’t let the Eclipse window lose focus, or it will cease to allow you to tab through the variables.

They seem a bit simple, and to some extent they are, but Eclipse templates can be handy for certain situations. I’ve made a few dozen for projects I am working on, and feel like I’ve saved more than enough time to justify their creation.

Oh, and if you want to share the templates, they can be exported and imported in the same place in the Preferences window.