不查询同一张表时如何使用@formula

时间:2018-07-04 09:23:17

标签: spring hibernate

我正在尝试从@Vote实体的配置文件表中获取数据。

@Entity
@Table(name = "vote")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Vote implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;

@NotNull
@Column(name = "creation_date", nullable = false)
private Instant creationDate;

@Column(name = "number_of_points")
private Integer numberOfPoints;

@ManyToOne(optional = false)
@NotNull
@JsonIgnoreProperties("")
private User user;

@ManyToOne(optional = false)
@NotNull
@JsonIgnoreProperties("votes")
private Proposal proposal;

@Formula("(SELECT SUM(number_of_points) FROM VOTE WHERE VOTE.USER_ID = USER_ID)")
int totalVotes;

@Formula("(SELECT USER_POINTS FROM PROFILE WHERE PROFILE.USER_ID = 1)")
Long userVotes;

它可以在同一张表中使用,就像我在这种情况下要求表决数据一样。...

@Formula("(SELECT SUM(number_of_points) FROM VOTE WHERE VOTE.USER_ID = USER_ID)")
int totalVotes;

但当我询问时不是

@Formula("(SELECT USER_POINTS FROM PROFILE WHERE PROFILE.USER_ID = 1)")
Long userVotes;

,我找不到任何说明存在限制的文档。谢谢

PD:顺便说一下,SQL语句可在数据库中工作。

entity User{
}

entity Profile {
    creationDate Instant required
    image ImageBlob
    userPoints Long min(100)
}

entity Vote {
    creationDate Instant required
    numberOfPoints Integer
}

// RELATIONSHIPS:
relationship OneToOne {
    Profile{user(id) required} to User{profile}
}

relationship ManyToOne {
    Vote{user(id) required} to User
}

1 个答案:

答案 0 :(得分:0)

尝试这种方法,希望它对您有用。

    @ManyToOne
    @JoinColumnsOrFormulas({
        @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT r.id FROM Result r WHERE resultDate = (SELECT MAX(sqr.resultDate) FROM Result sqr WHERE sqr.test_id = id))", referencedColumnName="id")),
    })
private Long userVotes;