Should raw Hibernate annotated POJO's be retur

2020-04-16 19:12发布

问题:

I understand separating the data layer objects (DAOs) in their own layer that abstracts the data access logic and data source specifics from service and business layers as outlined in DAO and Service layers (JPA/Hibernate + Spring) and other questions. I have experience creating these layers, but I've always used either raw JDBC or similar lower level ways of interfacing with the DB (such as Spring's SimpleJDBC), and am new to Hibernate.

My question comes in that in raw JDBC or other ways where you are actually dealing with a result set (or a thin wrapper around it) at the data access layer, the resulting POJOs where you stick your data are extremely clean and know nothing about where the data came from, and I've never worried about returning these to the service layer and beyond. However it appears that with Hibernate, you have a lot of your Hibernate / data structure specific logic right in the POJO annotations (things like 1 to many mappings, lazy loading preferences, etc). I feel uncomfortable returning them (or Collections of them) from my DAOs and up to my service layer and am tempted to have all the POJOs implement interfaces that I pass back instead. Is this good practice, or over complicating?

回答1:

Annotations have one drawback of coupling some framework knowledge with Java objects. That's the price you pay for not having separate metadata definitions. POJOs still remain POJOs, though, and from practical standpoint I see no good reason to complicate design just because of annotations.

Lets think, if you would use XML mappings, would you even have that concern? Most likely - not. So pay the penalty and move on; and in unlikely case if you will be changing your persistence framework - you will go ahead and remove those annotations. In all cases they should have no side effects on your code outside of your DAO layer.

Just my 2 cents...



回答2:

Both ;) I'm pretty ambivalent--I prefer interfaces, it's just easier to mock, use across non-Hibernate systems, etc. but in my case I've usually needed to provide an external API with datatypes, so it's almost always made sense. That, and I generate the interfaces automatically, so I don't have to actually do anything.

For isolated systems with no external API requirements, or if you never need the types outside of Hibernate, I'm not convinced it really matters all that much, although the purists will have my head on a pike for saying so (and they're arguably correct).