Mixing JPA annotations and XML configuration

前端 未结 3 1278
萌比男神i
萌比男神i 2021-01-14 17:44

I have a fairly large (new) project in which we have annotated many domain classes with JPA mappings. Now it is time to implement many named queries -- some entities may ha

3条回答
  •  逝去的感伤
    2021-01-14 18:32

    Is this possible?

    Yes it is, but the trend is more to centralize things, not the inverse.

    More importantly, is this reasonable?

    I am not annoyed by a having a block of annotations at the top of my entities class files. Actually, I like to have my queries where I think they belong: next to entities. I also like the compile time checks (on entity names, attributes) and the code completion I get when writing queries in the Java code (not sure my IDE would do that with xml mappings). In other words, I don't feel the need and don't want to externalize queries .

    Are there better approaches?

    I believe that using annotations is the best practice1.

    How is this done?

    The recommendation is to use XML mapping files only for native SQL statements that are specific to a particular database (of course, I omit the obvious case of legacy code that you can't annotate). In other words, use annotations but keep the code as free from vendor-specific stuff as possible.

    1 The JPA 1.0 specification co-lead Mike Keith covered many of the trade-offs associated with an XML metadata strategy (XML strategy) versus an in-source metadata strategy (annotations strategy) in the OTN column "To Annotate or Not". Sadly, I couldn't find a non-dead link to his publication. Maybe you'll be more lucky and in that case, read it.

提交回复
热议问题