Search code examples
javahibernatespring-data-jpajpql

JPA how to find top 500 in a answer table where the user table is a join and we are looking for answers where userid equals something


The question regards the JPA syntax as in findTop500... the rest I cant figure out. I have tried following with errors and looked through stack with no specific answers regarding autogenerated JPQL. A custom query is not sufficient for this task:

List<Answer> findTop500ByOrderByIdanswerDescWhereUserIduser(@Param("iduser")  long iduser);

&

List<Answer> findTop500ByIdanswerWhereUserIduserOrderByIdanswerDesc(@Param("iduser")  long iduser);

Answer table:

@Entity
@Table(name="answer")
public class Answer {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name="Idanswer")
    private long idanswer;


 @ManyToOne
    @JoinColumn(name = "Useriduser", referencedColumnName = "Iduser")
    private User user;
}

User table:

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="Iduser")
    private long iduser;

}

Solution

  • You have to create it like that:

    List<Answer> findTop500ByUserIduserOrderByIdanswerDesc(long iduser);
    

    You have to base on your entity mapping so -> BY user.iduser