spring-data-jpa Hibernate @Query在“”处或其附近抛出语法错误,

gtlvzcf8  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(154)

我尝试从实体Article中获取字段tags

@Getter
@Setter
@Entity
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "articles")
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Embedded
    private Author author;

    @Column(unique = true)
    private String title;

    private String content;

    @ElementCollection(targetClass = String.class,
            fetch = FetchType.EAGER
    )
    @CollectionTable(name = "tags",
            joinColumns = @JoinColumn(name = "article_id")
    )
    @Column(name = "tag")
    private List<String> tags = new ArrayList<>();
}

对于ArticleRepository extends JpaRepository<Article, Long>, JpaSpecificationExecutor<Article>@Query

@Query("SELECT " +
        " new java.util.ArrayList(a.tags) " +
        " FROM Article a " +
        " WHERE a.title = :title")
List<String> findAllTagsOfArticle(String title);

并得到一个结果:

Hibernate: 
    select
        . as col_0_0_ 
    from
        articles article0_ 
    inner join
        tags tags1_ 
            on article0_.id=tags1_.article_id 
    where
        article0_.title=?
2022-07-21 15:17:24.666  WARN 2196 --- [   scheduling-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42601
2022-07-21 15:17:24.666 ERROR 2196 --- [   scheduling-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: syntax error at or near "."

生成的SQL查询看起来正确,但在SELECT休眠后生成.
为什么会发生这种情况?如何解决?

cgh8pdjw

cgh8pdjw1#

你不能像这样传递一个集合(a.tags)。其思想是构造函数将从查询结果中接收一行。但是,也没有必要使用new ArrayList
这应该可行:

@Query("select t from Article a join a.tags t where a.title = :title")
List<String> findAllTagsOfArticle(String title);

您还可以稍微简化Map:

@ElementCollection
    @CollectionTable(name = "tags",
            joinColumns = @JoinColumn(name = "article_id")
    )
    @Column(name = "tag")
    private List<String> tags = new ArrayList<>();

在这种情况下,不需要指定EAGER和目标类。

相关问题