简体   繁体   中英

Java config for Hibernate/JPA?

As far as I know, there are two ways to configure JPA / Hibernate:

  • XML based configuration through something like hibernate.cfg.xml. I don't like his approach because, well, XML ...
  • Through annotations in the entity object. Much better than the XML config, but it couples my entities to JPA.

As I am currently investigating an architecture where the domain model does not know anything about the database (The 'Onion' architecture), I am looking for is a way to specify the mappings without changing my entities.

Of course I could create separate mapping classes, eg if I have a Customer domain object, create a JPA-annotated CustomerEntity and let the repository translate from one to another. But this approach doesn't feel quite right because the Customer and CustomerEntity will essentially be the same.

So it seems like I have to resort to Hibernate XML configuration, but as mentioned before, I don't like that approach. Spring has a nice way of configuration: Java-based configuration. I was wondering if there is something similar for Hibernate/JPA configuration, and if not, why not?

My apologies if none of the above makes sense, but any help is welcome, even if it doesn't answer my question :-)

I've never heard of an Onion Theory of Java EE design. I did hear of The Onion , but that's a satirical newsletter (if that :-). Separation of concerns in Java EE I typically expressed as a MVC, or Model View Controller architecture. Your JSP or JSF pages will be your view, your @ManagedBean controllers will be your controllers, and your model will hold your Entities.

The model, which is where the JPA will be, can usually be further separated into a Service Layer , a Persistence Layer and EIS (Enterprise Information System) or Database tier. The Service tier will hold your EJBs, annotated with Stateless , Statefull or Singleton , and will encapsulate the business logic for the application. The Persistence Layer will have @Entity annotated objects that are stored by the Database.

Java EE defines these layers with JSR's, with numbers of some sort. For example, the Java Persistence API (JPA) is JSR-220. Tests are developed against these JSR's and if a vendor meets these tests then their product can be (More or less) swapped out for another vender's version.

Apparantly there is somethinig called Fluent NHibernate for C#, which does exactly what I was looking for.

Unfortunately, there seems to be no "Fluent Hibernate" for Java.

There is a fluent-hibernate project on GitHub, but that one seems to be about fluently writing HQL-queries, not about mapping configurations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM