12.2. Writing Seam applications in Groovy
Since Groovy objects are Java objects, any Seam component can be written and deployed with Groovy. You can also combine Groovy and Java classes in the same application.
12.2.1. Writing Groovy components
You will need to use Groovy 1.1 or higher to support annotations. The rest of this chapter shows how to use Groovy in a Seam application.
12.2.1.1. Entity
Example 12.1. Using Groovy in a Seam Application
@Entity @Name("hotel") class Hotel implements Serializable { @Id @GeneratedValue Long id @Size(max=50) @NotNull String name @Size(max=100) @NotNull String address @Size(max=40) @NotNull String city @Size(min=2, max=10) @NotNull String state @Size(min=4, max=6) @NotNull String zip @Size(min=2, max=40) @NotNull String country @Column(precision=6, scale=2) BigDecimal price @Override String toString(){ return "Hotel(${name},${address},${city},${zip})" } }
Since Groovy supports properties, there is no need to explicitly write verbose getters and setters. In the previous example, the hotel class can be accessed from Java as
hotel.getCity() — the getters and setters are generated by the Groovy compiler. This makes the entity code very concise.
12.2.2. Seam component
You can write Seam components in Groovy exactly as you would in Java: annotations mark classes as Seam components.
Example 12.2. Writing Seam Components in Groovy
@Scope(ScopeType.SESSION) @Name("bookingList") class BookingListAction implements Serializable { @In EntityManager em @In User user @DataModel List<Booking> bookings @DataModelSelection Booking booking @Logger Log log @Factory public void getBookings() { bookings = em.createQuery(''' select b from Booking b where b.user.username = :username order by b.checkinDate'''). setParameter("username", user.username). getResultList() } public void cancel() { log.info("Cancel booking: #{bookingList.booking.id} for #{user.username}") Booking cancelled = em.find(Booking.class, booking.id) if (cancelled != null) em.remove( cancelled ) getBookings() FacesMessages.instance().add("Booking cancelled for confirmation number #{bookingList.booking.id}", new Object[0]) } }
12.2.3. seam-gen
Seam-gen interacts transparently with Groovy. No additional infrastructure is required to include Groovy code in seam-gen-backed projects — when writing an entity, just place your
.groovy files in src/main. When writing an action, place your .groovy files in src/hot.