使用 OneToMany 的 Spring Boot JPA 自定义查询

我正在 Spring Boot 中构建一个类似 Twitter 的应用程序。我正在尝试为用户生成时间线。我为此做了一个自定义查询,并将其添加到我的repositorywhich extends 中CrudRepository<Account, Long>。当我尝试启动应用程序时,我收到以下异常:


Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: account_following is not mapped

account_following 表是@OneToMany从Account到的Account,您可以在下面的代码中看到。我不确定如何将 放入account_following查询中。


帐户存储库.java


@Repository

public interface AccountRepository extends CrudRepository<Account, Long> {


    @Query("SELECT t FROM Tweet t, account_following k WHERE k.following_id = t.owner_id AND k.account_ID = :account_ID AND k.following_id IN (SELECT following_ID FROM account_following WHERE account_id = :account_ID) ORDER BY unixdate DESC")

    public List<Tweet> generateTimeline(@Param("account_ID") Long account_ID);


}

账号.java


@Entity

public class Account implements Serializable {


    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;


    @Column(unique=true)

    private String username;


    @Transient

    private String password;


    private String location;


    private String description;


    private String website;


    @OneToMany(cascade = CascadeType.ALL)

    private List<Account> following;


    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)

    private List<Tweet> tweets;

}

该表account_following存在于数据库中,如下图所示。我正在使用MySQL version 8.0.12.

http://img2.mukewang.com/6141994700017cf302170100.jpg


aluckdog
浏览 304回答 2
2回答

波斯汪

尝试将查询更改为本机查询。@Repositorypublic interface AccountRepository extends CrudRepository<Account, Long> {@Query(value= "SELECT t FROM Tweet t, account_following k WHERE k.following_id = t.owner_id AND k.account_ID = :account_ID AND k.following_id IN (SELECT following_ID FROM account_following WHERE account_id = :account_ID) ORDER BY unixdate DESC",nativeQuery=true)public List<Tweet> generateTimeline(@Param("account_ID") Long account_ID);}由于没有名为account_following 的实体,您会在 HQL 中收到该错误。

杨魅力

如果 JPQL:SELECT&nbsp;t&nbsp;FROM&nbsp;Tweet&nbsp;as&nbsp;t,&nbsp;Account&nbsp;as&nbsp;account&nbsp;WHERE&nbsp;account.following&nbsp;as&nbsp;f&nbsp;on&nbsp;f.id&nbsp;=&nbsp;t.ownerId&nbsp;...请注意,上述字段必须与类字段相同,而不是数据库中的列名。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java