spring boot jpa criteria api是如何生成JPQL的
当我们使用entityManager.createQuery(query)时,我们发现entityManager的注入对象如下:
也就是它:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@40383b24的一个代理对象。也是一个FactoryBean.
通过这个FactoryBean就可以创建出实际代理的对象:
// Determine current EntityManager: either the transactional one // managed by the factory or a temporary one for the given invocation. EntityManager target = EntityManagerFactoryUtils.doGetTransactionalEntityManager( this.targetFactory, this.properties, this.synchronizedWithTransaction); if (method.getName().equals("getTargetEntityManager")) { // Handle EntityManagerProxy interface. if (target == null) { throw new IllegalStateException("No transactional EntityManager available"); } return target; }
最终调用的就是org.hibernate.internal.SessionImpl#createQuery(javax.persistence.criteria.CriteriaQuery<T>)
@Override @SuppressWarnings("unchecked") public <T> QueryImplementor<T> createQuery(CriteriaQuery<T> criteriaQuery) { checkOpen(); try { return (QueryImplementor<T>) criteriaCompiler().compile( (CompilableCriteria) criteriaQuery ); } catch ( RuntimeException e ) { throw exceptionConverter.convert( e ); } }
compile方法的最后,可以看到:
return criteria.interpret( renderingContext ).buildCompiledQuery( entityManager, new InterpretedParameterMetadata() { @Override public Map<ParameterExpression<?>, ExplicitParameterInfo<?>> explicitParameterInfoMap() { return explicitParameterInfoMap; } @Override public List<ImplicitParameterBinding> implicitParameterBindings() { return implicitParameterBindings; } } );
org.hibernate.query.criteria.internal.CriteriaQueryImpl#interpret方法代码如下:
@Override public CriteriaInterpretation interpret(RenderingContext renderingContext) { final StringBuilder jpaqlBuffer = new StringBuilder(); queryStructure.render( jpaqlBuffer, renderingContext ); renderOrderByClause( renderingContext, jpaqlBuffer ); final String jpaqlString = jpaqlBuffer.toString(); log.debugf( "Rendered criteria query -> %s", jpaqlString ); 。。。。
这里就看到了JPQL了。
继续找render方法:
public void render(StringBuilder jpaqlQuery, RenderingContext renderingContext) { renderSelectClause( jpaqlQuery, renderingContext ); renderFromClause( jpaqlQuery, renderingContext ); renderWhereClause( jpaqlQuery, renderingContext ); renderGroupByClause( jpaqlQuery, renderingContext ); }