JPA 中的跨数据库联接
JPA 中可以进行跨数据库表连接吗?
我在一个数据库中有一个users
表,该表具有指向另一个数据库中的organizations
表的外键。两个数据库都位于同一台物理机器上。现在 MySQL 允许我编写跨多个数据库的查询,但我不知道如何使用 JPA 来做到这一点。
Java POJO 上的 @Entity
注释不采用数据库的名称,因此无法标记跨数据库关系。
对于这种情况有解决方法吗?也许使用本机查询来加载连接的实体?
Is it possible to do cross database table joins in JPA?
I have a users
table in one database which has a foreign key to a organizations
table in a separate database. Both the databases are on same physical machine. Now MySQL allows me to write queries which span across multiple databases, but I am not sure how to do this with JPA.
The @Entity
annotations on the Java POJO's don't take the name of the database so there is no way to mark a cross DB relationship.
Is there a workaround for this situation? Perhaps using a native query to load the joined entity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 MySQL 允许您编写跨数据库查询的 SQL,那么您可以在 JPA 的本机查询中使用此 SQL。
我假设您正在使用某种数据库链接机制?
如果是这样,那么您也应该能够映射它。您可以将链接数据库的@Table 上的“架构”设置为链接名称。
IE
If MySQL allows you to write SQL that query across the database, then you can use this SQL in a native Query in JPA.
I assume you are using some kind of database linking mechanism?
If so, then you should be able to map this as well. You can set the "schema" on your @Table of the linked database to the link name.
i.e.
你不能。由于每个实体都绑定到持久性上下文,并且上下文又绑定到数据库。
如果数据库指的是同一服务器上的模式,您可以做两件事:
如果两个模式位于不同的数据库上,那么您必须在代码中手动进行连接。
有一个问题要问你。您提到的“外键”是真正的数据库外键还是逻辑FK?
You can't. As each entity is bound to an persistance context and the context is bound to a database.
If by databases you mean schemas on the same server you can do 2 things
If both schemas are on different databases, then you'll have to do the join manually in your code.
One quesion for you. The "foreign key" you mentioned, is a real DB foreign key or a logical FK ?
我们尝试了以下方法,似乎有效。
1) @Table 注释中没有 schema 属性
2) 为实体创建不同的 orm 文件,这些实体由它们所在的 schema 组成。
3)在每个orm文件中,您可以添加一个“my_schema”。
4) 在 persistence.xml 中包含各自 PU 中的 orm 文件
5) 如果您在测试期间需要不同的数据库,请创建类似的 orm 文件进行测试并相应地更改模式中的值,并将这些 orm 文件包含在单独的 PU
HTH中
We tried out the following approach and seems to work.
1) No schema attribute in the @Table annotations
2) create different orm files for entities clubbed by the schema in which they are present.
3) In each of the orm files, you can add a "my_schema".
4) Include the orm files in your respective PUs in the persistence.xml
5) And if you want different databases during tests, create similar orm files for test and change the value in the schema accordingly and include these orm files in a separate PU
HTH