adam bien's blog

12 Tips On JPA Domain Modelling - With Existing Database - Thinking In Structs Not Objects 📎

  1. Forget about OO, DSLs, encapsulation, think in structs. Try to as frictionless as possible export/generate the JPA-entities from the existing database. It works perfectly with Netbeans (context menu -> new entity classes from database), or Eclipse Dali.
  2. Implement a very thin facade / transaction boundary. Currently the simplest possible way is a @Stateless Bean (EJB 3).
  3. Write rudimentary integration tests with e.g. Junit. Purpose: JPA mapping verification.
  4. Execute the "Unit" tests after every change.
  5. Implement and perform load / stress tests.
  6. If your database will remain the "master", go to 1 on every DB schema change. If it is worth to invest in real objects, then:
    1. Rename the classes into some more meaningful. The attribute, class names are in general everything but not fluent. Goto 4. This change will break the JPA queries.
    2. Rename the getters / setters - even better get rid of them (this should not break the queries, unless you are working with property based access which is not recommended). Goto 4.
    3. Goto 5.
    4. If the JPA entities still do not look right, try to apply some JPA tricks like mapping a JPA-entity to several tables, or even map JPA-entities to DB-views, to improve the situation. Goto 4.
    5. Goto 5. Compare the results with 9.
    6. Remember everything what you forgot in 1 again. Now your domain objects are semi-objectoriented. You could even start with OO-modelling.

Disclaimer: The gotos are actually gosubs (for ZX Spectrum / C64 geeks :-))

[Rich and anemic domain objects are discussed in-depth in the "Real World Java EE Patterns" book. See e.g. page 83 and 259]