Loading JPA Entity from external Jar file

前端 未结 4 1941
清酒与你
清酒与你 2020-12-16 03:01

i have a project setup where i have modularized a project, and packaged a module into a jar file which gets included in the main project when we create a war and deploy it.

相关标签:
4条回答
  • 2020-12-16 03:26

    At work we don't use JPA but Hibernate, and our project is totally modularized. We handle about 30 countries which do not use the same modules, and we are able to load all these module's entities in a session factory by simply changing the maven dependencies (no orm file to modify)

    The solution used is to use the Java SPI. The ServiceLoader will lookup for classes that implement a core interface EntityProvider. Each EntityProvider of every module will hardcode the entities it brings and return a list of entities when calling ServiceLoader.load(EntityProvider.class). Thus in the platform core we just need to create a spring based session factory in which we provide the entities list by a factory bean which will call the SPI.

    I don't know if it will be easy with JPA but i'm pretty sure it's possible but you may need to create manually the EMF from a spring context, and also the PersistenceUnit i guess... What you may want is a persistence unit that is a "merge" of the persistence units of all your modules (at least for your entities) Take a look at SPI and also the javax.persistence.spi package.

    Check also how to create an EMF with Spring: AbstractEntityManagerFactoryBean

    Edit: you can check this: using the MergingPersistenceUnitManager to load entity

    0 讨论(0)
  • 2020-12-16 03:29

    if you are using spring boot use the entity scan annotation in your main springboot class

    @EntityScan(
            basePackageClasses = {externalpackage.classname.class}
    )
    
    0 讨论(0)
  • 2020-12-16 03:40

    Simply use

    @EntityScan("com...pakage-which-contains-entities...")
    

    Or if you have multiple entities packages, use

    @EntityScan(basePackages = {"...pkg1...", "...pkg2..."} )
    
    0 讨论(0)
  • 2020-12-16 03:41

    To scan entities residing in jar, you have to include it in persistence.xml. <jar-file>packedEntity.jar</jar-file>.

    If you want to load unit from the package, then you can try directly injecting it from jar. @PersistenceContext(unitName = "../packedEntity.jar#main")

    Haven't tried but you can enable hibernate auto detection for entities <property name="hibernate.archive.autodetection" value="class, hbm"/>

    0 讨论(0)
提交回复
热议问题