简体   繁体   中英

JPA criteria JOIN: what does {oj …} mean in SQL?

I learn JPA and tried the following code:

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);

So one person has many contacts. The code is working. I use H2 database and EclipseLink. However, I can't understand what {oj...} means in SQL. Explain please.

This is the generated 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 = ?)

This is not specific to JPA or SQL, but it is part of the JDBC specification. The JDBC specification contains a number of escapes that are intended to address (potential) incompatibilities between SQL implementations. Drivers are expected to translate this to the database specific SQL.

The {oj <join-definition>} is an escape for an outer join.

To quote from the JDBC 4.2 specification section 13.4.3 Outer Joins:

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 following SELECT 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 , and supportsLimitedOuterJoins .

Nowadays almost all databases support the SQL standard outer join syntax, so most drivers will simply remove the {oj and } around this. However other JDBC escapes still have their place to address differences between databases.

Interestingly, as a JPA implementation usually knows the specific database in use, I would have expected this to generate database specific SQL instead of using the form with JDBC escapes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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