Equinox (OSGi) and JPA/Hibernate - Finding Entities

前端 未结 2 1416
情话喂你
情话喂你 2021-01-06 08:30

I am trying to use Hibernate/Spring in an OSGi (Equinox) environment. It works great if I explicitly point it to the Entity classes in the Persistence.xml:

         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 09:28

    The previous reply mentioning the OSGi blog entry on the problems of Hibernate and OSGi is an informative read.

    I suggest stepping back and thinking about the assumptions that are true in a traditional Java application and how they are no longer valid inside OSGi:

    OSGi is dynamic

    How will your application work if the Hibernate bundle is started before any bundles that provide the entity classes? Even if the scanning for entity classes worked, it wouldn't find any.

    In traditional Java all the classes are available at start-up because of the flat class path, but in OSGi classes are only available if the contributing bundle is started and you import the packages.

    Explicit Dependencies

    OSGi requires explicit wiring of dependencies; if you don't import a bundle/package, then you can't see the classes in those bundles/packages.

    Since you say that explicitly configuring the entity classes work, I assume you are using one of the following to do the dependency wiring:

    • Import-Package
    • Require-Bundle
    • Dynamic-Import
    • Equinox's buddy policy

    Rich Seller's suggestion should work (I haven't tested it), but you are still forced to import the packages containing the entity classes, though I see nothing wrong with this and the proposed solution gives the option for package scanning rather than explicitly specifying every single entity class.

    Suggestions

    1. Use Rich Seller's solution, but be aware that the solution is not dynamic (this might not matter for your application).
    2. Implement the extender pattern for entity classes so that you can re-create the Hibernate session factory when entity-contributing bundles start and stop.

    Now option 1 is easy and option 2 involves a whole lot of work. It all depends on your requirement for automatic adding/removing of entity classes from Hibernate without needing to explicitly specify packages/classes.

提交回复
热议问题