简体   繁体   English

JPA实体映射来自不同的持久单元

[英]JPA entity mapping from different persistent unit

Is there any specific configuration to put an entity from different persistence Unit into a current mapping? 是否有任何特定的配置将实体从不同的持久性单元放入当前映射?

For example: 例如:

@RooJpaActiveRecord(persistenceUnit = "persistenceUnit_central")
public class UserGroups{

    //users come from `persistenceUnit_client`
    //how to work this out?
    //can mappedBy and targetEntity works the same way
    //as they are in the same persistence unit?
    @OneToMany
    private List<User> users;
}

Thanks in advance. 提前致谢。

I don't think you can't do it straightforward. 我认为你不能直截了当地做到这一点。 Persistence units mean to be distinctly separate; 持久性单位意味着明显分开; they have different entity managers, so they may well be (and this is usually the reason) from different databases or schemas. 他们有不同的实体经理,所以他们很可能(这通常是因为不同的数据库或模式)。

You still can define the same entity class to be present in several persistence units, in persistence.xml , but, as I said, it will be handled by each manager separately. 您仍然可以定义相同的实体类存在于一些持久性单元,在persistence.xml中,但是,正如我所说,将每个经理单独处理。 This means you can't do this: 这意味着你不能这样做:

UserGroups ug = em1.find(UserGroups.class, ...); // entity manager 1
User u = em2.find(User.class, ...); // entity manager 2

// exception will be thrown on commit 
// - from the point of view of em1, "u" is detached
ug.getUsers().add(u); 

I'm not sure if calling em1.merge(u) would solve the problem — I haven't yet come across such situation. 我不确定是否会调用em1.merge(u)来解决问题 - 我还没有遇到过这样的情况。 But you surely can create a copy of User and merge it into desired persistence context. 但是你肯定可以创建一个User副本并将其合并到所需的持久化上下文中。

MaDa is correct. 妈妈是对的。 I made this answer to the question is just to hightlight the solution to this issue. 我对这个问题的回答只是为了解决这个问题。

First we so far we cannot persist instance of entity A within entity B while A and B are from different persistence Unit. 首先,我们到目前为止我们不能在实体B中保持实体A的实例,而A和B来自不同的持久性单元。 A safe way to make it work properly is to make instance of entity A becomes @Transient, then there will never get a change to make that instance tie to the database. 使其正常工作的一种安全方法是使实体A的实例变为@Transient,然后永远不会进行更改以使该实例与数据库绑定。 However, it will be a little bit pain to manually set up the relationship between the entities(setter and getter), that becomes an open question. 但是,手动设置实体(setter和getter)之间的关系会有点痛苦,这就成了一个悬而未决的问题。

Thanks again Mada. 再次感谢Mada。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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