我尝试从实体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
休眠后生成.
为什么会发生这种情况?如何解决?
1条答案
按热度按时间cgh8pdjw1#
你不能像这样传递一个集合(
a.tags
)。其思想是构造函数将从查询结果中接收一行。但是,也没有必要使用new ArrayList
。这应该可行:
您还可以稍微简化Map:
在这种情况下,不需要指定
EAGER
和目标类。