Are persistence annotations in domain objects a bad practice?

前端 未结 8 924
青春惊慌失措
青春惊慌失措 2021-02-01 15:09

I realize that persistence frameworks such as Morphia and Hibernate rely on annotations on domain objects to do their magic. At some level, it seems to me that this is insertin

8条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 15:28

    Short answer: I like persistent, rich, domain objects.

    Long answer:

    For nearly 10 years I worked on a fairly large system ~ 500k LOC using Spring and Hibernate. At the beginning, we started with a "transaction script" (see Fowler) approach, partly because we didn't quite trust Hibernate. However, in a short time, we came to trust Hibernate and due to my much earlier training in fairly purist OO, I became a big believer in transient persistence combined with a Domain Driven Design approach. We basically came to think of our system as being backed with an ODBMS (with plenty of small leaks :-)).

    I called our architecture a "domain kernel" because the book DDD had not been written yet. This was in the early days of Hibernate, so the domain model was not polluted with annotations. The separate concern of persistence was kept separate in XML mappings.

    Again, over time, we got better at pushing behavior down into the domain layer. We had a pretty traditional controller-->service-->dao-->domain layering scheme that was enforced with compile-time dependencies. What I observed over time is that this model worked very well for our system, which represented every facet of the fairly complex domain of 401(k) plan management, including plan setup, trading, accounting, compliance testing, sales, branding, etc. A rich domain model with (relatively) transparent "magical" persistence was key in our being able to build new features in terms of existing features in the domain model.

    Our service layer only orchestrated the interactions between technical services (such as email, file I/O, queuing, etc.) and helped to span domain packages when necessary. The service layer also defined the transaction boundary (via Spring). Services only received or emitted DTOs or primitives. A lot of people hate that, as a break in DRY, but we found it kept us honest when defining the service interfaces and the code that used them. It also made it very easy to remote things later.

    This approach allowed us to build high-quality software with a pretty small team (we were a Scrum team).

    So, consider me a believer in persistent domain objects. Don't know if my story helps, but I wanted to share.

提交回复
热议问题