Equinox (OSGi) and JPA/Hibernate - Finding Entities

前端 未结 2 1413
情话喂你
情话喂你 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:16

    This blog shows how it can be handled with Spring's Dynamic Modules. Based on that blog, you'd create bean definitions for DAO and Service beans in your application context. The DAO has a reference to the hibernate sessionFactory bean:

    
      
    
    
      
    
    
    
    

    The StuffSourceDaoImpl would implement the store() method to persist the StuffSource, it passes the StuffSource to the HibernateTemplate to actually do the persistence.

    To avoid having to define persistence.xml files or specifying every Entity, you can use the AnnotationSessionFactoryBean and a wildcard to include all the types in the package(s) containing your entities (you may instead want to set the packagesToScan property, I've not tried this and it might take you back to your original problem):

    
      
        
          
        
      
      
      
        
          com.es.t.eee.domain.StuffSource
          com.es.t.eee.domain.PostalAddress
        
      
      
        
          com.es.t.eee.domain
        
      
    
    

    To use this you'd get the BundleContext, get the service and bean from the context, then carry on as normal:

    String serviceName = StuffService .class.getName();
    StuffService service = 
      (StuffService )context.getService(context.getServiceReference(serviceName));
    
    String stuffName = StuffSource.class.getName();
    StuffSource stuffSource = 
      (StuffSource) context.getService(context.getServiceReference(stuffName ));
    
    //do whatever with StuffSource
    ...
    
    service.store(stuffSource );
    

    You may also want to look at this OSGi Alliance blog that discusses some of the issues involved. From the OSGi Alliance blog:

    Hibernate manipulates the classpath, and programs like that usually do not work well together with OSGi based systems. The reason is that in many systems the class visibility between modules is more or less unrestricted. In OSGi frameworks, the classpath is well defined and restricted. This gives us a lot of good features but it also gives us pain when we want to use a library that has aspirations to become a classloader when it grows up. ...

    To work with Hibernate, you need a Session object. You can get a Session object from a SessionFactory. To get the the SessionFactory, you need to create it with a Configuration object. The Configuration object is created from a configuration XML file. By default, Hibernate loads this from the root of your JAR file, however, you can add classes manually to the configuration if so desired.

提交回复
热议问题