Spring JPA中方法名称中支持的关键字

时间:2016-05-04 10:32:07

标签: java spring hibernate jpa spring-data-jpa

如何为以下查询编写方法名称:

@Query("SELECT r.skill, r.rating, count(r) FROM AssociateRating r "
    + "where updatedTime = ( select max(updatedTime) from AssociateRating a "
    + "where r.associate = a.associate ) GROUP BY r.skill, r.rating")
List<Object[]> findCountMostRecent();

请在下面找到型号:

@Entity
@Table(name = "associate_ratings")
public class AssociateRating {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String associate;

    @ManyToOne
    @JoinColumn(name = "skill_id")
    private Skill skill;

    private int rating;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_time")
    private Date updatedTime;


    public long getId() {
        return id;
    }

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

    public String getAssociate() {
        return associate;
    }

    public void setAssociate(String associate) {
        this.associate = associate;
    }

    public Skill getSkill() {
        return skill;
    }

    public void setSkill(Skill skill) {
        this.skill = skill;
    }
    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public Date getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(Date updatedTime) {
        this.updatedTime = updatedTime;
    }
}


/**
 * Skill Model
 */
@Entity
@Table(name = "skills")
public class Skill {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

     public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

我在尝试从associate_ratings中提取记录时遇到异常 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:未知列&#39; updatedTime&#39;在&#39; where子句&#39;

你能告诉我这里有什么问题吗? 您能否告诉我如何在这种情况下命名Spring JPA findXX方法?

1 个答案:

答案 0 :(得分:0)

确实,您的表中没有'updatedTime'列。

列名称为“ updated_time ”,如@Entity updatedTime变量所示。

现在,如果您想使用JPA关键字创建方法名称,我想您的查询中不可能出于以下几个原因:

  • 您无法选择特定列(r.skill,r.rating,count(r)),但您应该全部选择它们。
  • 您不能拥有嵌套查询。
  • 没有GroupBy关键字

您可以在此处找到所有JPA支持的关键字:2.3 Query methods

所以在你的情况下,你应该采用@Query方法。