为一个实体使用两个实体管理器

Use two entity managers for one entity

情况如下:我有两个数据库 Db1Db2,我有两个 EntityManagers em1em2 定义。此外,我将实体 Person(int id, String name, Pet pet) 映射到数据库 Db1 中的 table persons(id, name) 和实体 Pet(int id, String name, Person owner) 映射到数据库 db2 中的 table pets(id, name, person_id)。 Person 和 Pet 之间的关系是一个@OneToOne 关系。在程序的某个时刻,我想做这样的事情:

PersonDAO personDAO = db1DAOFactory.getPersonDAO();
Person person = personDAO.find(100);
System.out.println(person.getPet().getName());

无法合并两个数据库。我如何告诉 Hibernate 将 EntityManager em2 用于 pet 字段?对于 Hibernate,我只使用注解,没有 xml 配置。

非常感谢!

抱歉,我认为你不能。 nakosspy:

回答了这个问题

Hibernate will create an SQL query for your HQL or Criteria query and this SQL will be sent through jdbc to the database. This means that hibernate does not support for what you are trying to do.

However, you can achieve the same result in some cases. Some databases give you the option to create an alias for a table that resides in a different database. So you will be able to write an SQL query that joins the two tables and execute it on the database.

We are doing that with DB2. If you can do that, it depends on your database.

I guess, that it would impossible if you have two different databases (example DB2 and MySQL) but if both databases are of the same vendor, then maybe it's achievable.

You should try to find more info in you database server's documentation.

如果你想看他的原作 post 请查看此 link

这取决于数据库功能。如果您使用的是 Oracle 数据库,您可以通过在数据库中创建 db link 然后通过在 oracle 数据库中创建视图或同义词来映射这些实体来实现此目的。检查您的数据库功能。希望这有帮助。