Friday, June 4, 2010

Eclipse Code Templates for JPA

I'm a lazy programmer or so called "copy-paste" programmer, always write code by edit previous code copy. Especially when they are tedious, repeated database CRUD operation. There are some quick develop tools, such as Appfuse and Spring Roo which, can generate basic code. But it is unavoidable to create some specific query operation by hand. I did a lot of copy&paste and finally find eclipse's code template can do this job for me.

To add your own code template, go to Windows->Preferences->Java->Editor->Templates
Then click "New".


put this code into "Pattern":
${:import(javax.persistence.EntityManager,javax.persistence.Query)}  

  String select = "select o from ${name} o WHERE o.${argname}=:${argname}";
  Query query = entityManager.createQuery(select);
  query.setParameter("${argname}", ${argname});
  return query.setFirstResult(firstResult).setMaxResults(maxResults)
    .getResultList();

When you need to use jpa query, type "jpaquery" and press "ctral+space" to fire code assistant(I change the default shortcut key to "alt+.", use whatever you customized).

now you can see the template code appers and focus on "name" then it will go to "argname".

Wonderful, here is a little explanation about the code template:

1. This will add import EntityManager and Query in your code if they are not. Feel free to add import, eclipse will check if it existed before add.
${:import(javax.persistence.EntityManager,javax.persistence.Query)}  


2. ${name}, ${argname} are the variables. The good part is all the variable will be changed as you edit.

This tutorial will show you how to create JPA code template and you can apply it to other code you copy-paste repeatedly.

0 comments: