【问题标题】:Does Hibernate4.1 still support @Formula annotation?Hibernate4.1 还支持@Formula 注解吗?
【发布时间】:2013-01-21 15:12:18
【问题描述】:

我试图在我的 Hibernate4.1 实体类之一中使用 @Formula 注释。从一些文章中我了解到这个注释需要放在属性定义上,所以我这样做了。但是什么也没发生。不管公式内容多么简单,Hibernate 只是不停地将属性直接放入生成的 sql 中,然后抛出“invalid identifier”异常,因为物理表中显然没有该名称对应的列。

我只能找到一些关于如何使用@Formula 的文档,但没有一个文档提到 Hibernate4 是否仍然支持它。那么这个问题有确定的答案吗?我是否可以以一种或另一种方式使用此注释?

新增内容: 下面是示例代码:

package sample.model;

import java.math.BigDecimal;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Formula;


@Entity
@Table(name = "STAGE_TRACK", schema = "")
public class StageTrack implements java.io.Serializable {

    // Fields

    private BigDecimal id;
    private Date startTime;
    private Date endTime;

    @Formula("(END_TIME - START_TIME)*24*60")
    private BigDecimal duration;
    public BigDecimal getDuration() {
        return this.duration;

    }
    public void setDuration(BigDecimal duration) {
        this.duration = duration;
    }

    // Constructors
    /** default constructor */
    public StageTrack() {
    }

    /** minimal constructor */
    public StageTrack(BigDecimal id) {
        this.id = id;
    }

    /** full constructor */
    public StageTrack(BigDecimal id, Date startTime, Date endTime) {
        this.id = id;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    // Property accessors
    @Id
    @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0)
    public BigDecimal getId() {
        return this.id;
    }

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

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "START_TIME", length = 7)
    public Date getStartTime() {
        return this.startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "END_TIME", length = 7)
    public Date getEndTime() {
        return this.endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

}

【问题讨论】:

    标签: hibernate formula


    【解决方案1】:

    你的问题是你把@Formula放在一个字段上,而其他注释放在getter上,因此@Formula被忽略了。

    您应该选择一种策略并始终如一地应用它(除非您明确地用@AccessType 覆盖它)。

    @Formula("(END_TIME - START_TIME)*24*60")
    public BigDecimal getDuration() {
        return this.duration;
    
    }
    

    【讨论】:

    • 谢谢哥们。这正是我的问题所在!猜猜“@Formula 必须放在属性定义上”是错误信息;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多