JPA Entity - Specify Persistence Unit?

前端 未结 3 2086
长发绾君心
长发绾君心 2020-12-30 08:33

I have a JavaEE project that makes use of multiple persistence units. Is there any way to specify which persistence unit a particular JPA Entity belongs to? Some entities

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 09:20

    Also you can identify from which persistent unit an entity belongs by identifying the EntityManager that registered it.

    A managed entity belongs to a persistence context, and a persistent context belongs to a persistence unit. So in this example:

    @PersistenceContext(unitName="persistence-unit-1")
    EntityManager em1;
    
    @PersistenceContext(unitName="persistence-unit-2")
    EntityManager em2;
    
    em1.persist(entity1);
    em2.persist(entity2);
    

    entity1 belongs to persistence-unit-1 and entity2 belongs to persistence-unit-2. It's not so explicit like specifying the tags in persistence.xml, but you can have the same entity classes in both persistent units and still differentiate to which unit each entity instance belongs.

提交回复
热议问题