Spring Hibernate-使用@Formula从基于其他表的最大值中获取列值

时间:2020-10-07 18:52:33

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

我有两个具有一对多关系的表。铅和铅活性。线索可以进行多种活动。

问题陈述- 我希望销售线索表中的其他列知道任何销售线索的最后修改日期。上次修改日期将是创建或更新上一个活动的日期。因此,我正在使用@Formula来获取列。但是,我无法获取正确的日期,而是为lastModifiedDate字段获取了空值。任何人都可以帮我解决问题。下面是表结构

@Entity
@Table(name = "customer_lead")
@Where(clause = ReusableFields.SOFT_DELETED_CLAUSE)
@Audited(withModifiedFlag = true)
@Data
public class Lead extends ReusableFields implements Serializable
{
    //other fields 

    @NotAudited
    @Formula("(Select max(modified) from lead_activity la Where la.lead_id=lead_id)")
    Date lastModifiedDate;
}

领导活动

@Entity
@Table(name = "LeadActivity")
@Data
@Where(clause = ReusableFields.SOFT_DELETED_CLAUSE)
public class LeadActivity extends ReusableFields implements Serializable
{
    // other fields

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "lead_id", nullable = false)
    @JsonIgnoreProperties(
    { "hibernateLazyInitializer", "handler" })
    @NotFound(action = NotFoundAction.IGNORE)
    Lead lead;

}

用于修改字段的映射超类

@MappedSuperclass
@Audited
public class ReusableFields implements Serializable
{

    public static final String SOFT_DELETED_CLAUSE = "is_deleted = 'false'";

    
    @Column(name="is_deleted", columnDefinition="BOOLEAN DEFAULT true")
    public boolean isDeleted;

    @CreationTimestamp
    @Column(name = "created_at")
    @JsonProperty("created")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss ")
    private Date created;
    
    @Column(name = "updated_at")
    @JsonProperty("updated")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
    @UpdateTimestamp
    private Date modified;
    
    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getModified() {
        return modified;
    }

    public void setModified(Date modified) {
        this.modified = modified;
    }

    public boolean isDeleted() {
        return isDeleted;
    }

    public void setDeleted(boolean isDeleted) {
        this.isDeleted = isDeleted;
    }

    public static String getSoftDeletedClause() {
        return SOFT_DELETED_CLAUSE;
    }
    
}

1 个答案:

答案 0 :(得分:0)

通过添加以下公式来处理

@NotAudited @Formula(“(从Lead_Activity la中选择max(la.updated_at),其中la.lead_id = lead_id)”) 日期lastModifiedDate;