Ballmerpeak devblog

Software development, related stuff and others

Anti-patterns 1: @Transient fields vs. extender classes

September 06, 2015 — Richárd Thier
The well-known JPA object-relational mapping API enables you to think of database entities like (java) objects. When you search up your entities or query results, basically you get objects whose fields are in correspondance with the columns of the database table. That is very good so far, but sometimes one might use a returned object like this in a GUI application to bind a visible table for the elements or such and you can easily get into situations when you want to extend your entity with some fields that are not represented directly in the database, but you want to appear in the visible representation - or you have similar problems. For those cases one can just create a new class, that embed the JPA entity in itself and provide the new fields - or does not even embed the entity just copy the data from it - but seemingly there is an other possibility that might seem faster: Just adding new fields for the JPA entity and marking them with the @Transient annotation as that means the JPA framework will not take care of that field and its value will never be in the database. Seems right? I hope that I can make you sure to never design code like that unless you really need to use this functionality - it is EVIL! ;-)

In short: I will present with an example why one should try to ensure the entity classes are containing only data that will be stored in the database without added business fields that are never presented in the database. If you need such extra information, create a class that has your entity and the extra information or use DTO objects, but do not use @Transient in new designs when not necessary.

Read more...

Tags: software-technology, anti-pattern, jpa, java, transient, drawit, vim