adam bien's blog

JavaEE 7 Retired The DTO 📎

The classic DTO solves the following problem:

"You want to transfer multiple data elements over a tier."

Back in the days a DTO was implemented as a Serializable anemic Java class only equipped with field accessors.

In Java EE the https://jax-rs-spec.java.net became a de-facto standard for remoting, so the implementation of Serializable interface is no more required. To transfer data between tiers in Java EE 7 you get the following options for free:

  1. JAXB: the popular application servers offer JSON, XML serialization for "free".
    
    @Entity
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @NamedQuery(name = Registration.findAll, query = "SELECT r FROM Registration r")
    public class Registration {
    
        private static final String PREFIX = "com.airhacks.workshops.business.registrations.entity.Registration.";
        public static final String findAll = PREFIX + "all";
    
    
        @Id
        @GeneratedValue
        @XmlTransient
        private long id;
    
        @XmlTransient
        @Transient
        private BiFunction<Boolean, Integer, Integer> taxCalculator;
    
        private int numberOfDays;
        private int numberOfAttendees;
        private boolean vatIdAvailable;
        
        //...
    
    }
    
    
    [Registration.java from https://github.com/AdamBien/javaee-bce-archetype]
  2. With the introduction of Java API for JSON Processing, you can also directly serialize parts of your objects into JSON:
    
    @Path("health")
    @Produces(MediaType.APPLICATION_JSON)
    public class HealthResource {
    
        @Inject
        ServerWatch watch;
    
    
        @GET
        @Path("/current-memory")
        public JsonObject availableHeap() {
     JsonObjectBuilder builder = Json.createObjectBuilder();
    	builder.add("Available memory in mb", this.watch.availableMemoryInMB()).
    	add("Used memory in mb", this.watch.usedMemoryInMb());
    	return builder.build();
        }
        
        //...
    }
    
    
    [HealthResource.java from project ping]

Both approaches transport the data without any binary coupling to the origin object. The decoupling is even higher, as it was the case with the "traditional" (=code duplication) DTO implementation.

[See also an in-depth discussion in the "Real World Java EE Night Hacks--Dissecting the Business Tier" book, page 273 in, chapter "Data Transfer Object"]

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!