我学习了 JPA 并尝试了以下代码:
CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
CriteriaQuery<PersonDI> criteriaQuery = queryBuilder.createQuery(PersonDI.class);
Root<PersonDI> personDI = criteriaQuery.from(PersonDI.class);
Fetch<PersonDI, ContactDI> contactDI = personDI.fetch("contacts", JoinType.LEFT);
criteriaQuery.where(queryBuilder.equal(personDI.get("guid"), guids.get(0)));
criteriaQuery.select(personDI).distinct(true);
TypedQuery<PersonDI> query = em.createQuery(criteriaQuery);
所以一个人有很多联系人。该代码正在运行。我使用 H2 数据库和 EclipseLink。但是,我无法理解 {oj...}
在 SQL 中的含义。请解释一下。
这是生成的 SQL:
SELECT DISTINCT t1.col0, t1.col3, t1.col1, t1.col2, t0.col0, t0.col2 FROM {oj tbl0 t1 LEFT OUTER JOIN tbl1 t0 ON (t0.col1 = t1.col0)} WHERE (t1.col0 = ?)
最佳答案
这不是 JPA 或 SQL 特有的,但它是 JDBC 规范的一部分。 JDBC 规范包含许多转义符,旨在解决 SQL 实现之间(潜在的)不兼容问题。驱动程序应将其转换为数据库特定的 SQL。
{oj <join-definition>}
是外连接的转义。
引用JDBC 4.2 specification第 13.4.3 节外连接:
Outer joins are an advanced feature and are not supported by all data sources. Consult relevant SQL documentation for an explanation of outer joins.
The escape syntax for an outer join is:
{oj <outer-join>}
where
<outer-join>
has the form:table {LEFT|RIGHT|FULL} OUTER JOIN {table | <outer-join>} ON search-condition
(Note that curly braces (
{}
) in the preceding line indicate that one of the items between them must be used; they are not part of the syntax.) The followingSELECT
statement uses the escape syntax for an outer join.Statement stmt = con.createStatement(); stmt.executeQuery("SELECT * FROM {oj TABLE1 " + "LEFT OUTER JOIN TABLE2 ON DEPT_NO = 003420930}");
The JDBC API provides three
DatabaseMetaData
methods for determining the kinds of outer joins a driver supports:supportsOuterJoins
,supportsFullOuterJoins
, andsupportsLimitedOuterJoins
.
现在几乎所有数据库都支持 SQL 标准外连接语法,因此大多数驱动程序都会简单地删除 {oj
和}
围绕这个。然而,其他 JDBC 转义仍然可以解决数据库之间的差异。
有趣的是,由于 JPA 实现通常知道正在使用的特定数据库,因此我希望这会生成特定于数据库的 SQL,而不是使用带有 JDBC 转义的表单。
关于java - JPA 标准 JOIN : what does {oj . ..} 在 SQL 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190529/