简体   繁体   English

将SQL Left Join查询转换为EclipseLink JPA查询

[英]Translate SQL Left Join query to EclipseLink JPA query

I am trying to write a JPA NamedQuery. 我正在尝试编写一个JPA NamedQuery。 I have a working SQL query as follows: 我有一个正常的SQL查询,如下所示:

SELECT MIN(t1.Id + 1) AS nextID 
FROM 
    MyTable t1 LEFT JOIN MyTable t2 
ON 
    t1.Id + 1 = t2.Id
WHERE 
    t2.Id IS NULL

I am not able to translate this query to JPQL syntax. 我无法将此查询转换为JPQL语法。

I think doing such a custom join is not possible with standard JPQL. 我认为使用标准JPQL无法进行这种自定义联接。 I was looking for a possibility to do it some time ago and found that Hibernate offers a proprietary extension @JoinFormula to achieve this, cf. 一段时间前,我一直在寻找一种实现的可能,发现Hibernate提供了专有扩展@JoinFormula来实现这一目标,请参见。 Hibernate @JoinFormula . 休眠@JoinFormula But I couldn't find an equivalent for EclipseLink. 但是我找不到EclipseLink的等效项。

You might be able use a @NamedNativeQuery together with an @SqlResultSetMapping to map your SQL statement to a JPA entity, something like this: 你也许可以使用@NamedNativeQuery连同@SqlResultSetMapping到您的SQL语句映射到一个JPA实体,是这样的:

@NamedNativeQuery( name = "customJoin", 
                   query = "SELECT MIN(t1.Id + 1) AS nextID FROM MyTable t1 LEFT JOIN MyTable t2 ON t1.Id + 1 = t2.Id WHERE t2.Id IS NULL",
                   resultSetMapping = "customJoinMapping" )

@SqlResultSetMapping( name = "customJoinMapping",
                      entities = @EntityResult( entityClass = MyTable.class, fields = @FieldResult( name = "id", column = "nextID" ) ) )
@Entity
@Access( AccessType.Field )
public class MyTable {
   private int id;

   public int getId() {
      return this.id;
   }

   public void setId( int id ) {
      this.id = id;
   }
}

UPDATE UPDATE

Much later, I found a way to customize relationship joins in EclipseLink here . 后来,我找到了一种方法来定制关系的EclipseLink加入这里 The feature to use is a DescriptorCustomizer , which can be placed on a JPA entity with @Customizer . 使用的功能是DescriptorCustomizer ,可以使用@Customizer将其放置在JPA实体上。

In the customize() method, one can express additional join criteria using the EclipseLink Expression API. customize()方法中,可以使用EclipseLink Expression API表示其他联接条件。 For example, the following code fragment would produce the additional join criteria [...] AND TargetEntity.someAttribute IN ('V', 'W', 'U') (where someRelationship points to a TargetEntity ). 例如,以下代码片段将产生附加的连接条件[...] AND TargetEntity.someAttribute IN ('V', 'W', 'U') (其中someRelationship指向TargetEntity )。

OneToManyMapping mapping = (OneToManyMapping) descriptor.getMappingForAttributeName( "someRelationship" );
Expression origExp = mapping.buildSelectionCriteria();
ExpressionBuilder expBuilder = origExp.getBuilder();
Expression constantExp = expBuilder.get( "someAttribute" ).in( new String[] { "V", "W", "U" } );
Expression newExp = origExp.and( constantExp );
mapping.setSelectionCriteria( newExp );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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