使用复合主键映射表

时间:2013-01-29 17:56:03

标签: java hibernate jpa

我在hibernate中有以下实体,使用JPA注释

@Entity
@IdClass(PurchaseCounter.PurchaseCounterPK.class)
@Table(name = "customer_purchases_counter")
public class PurchaseCounter {


    public static class PurchaseCounterPK implements Serializable {

        Integer customerId;
        Integer purchaseId;

        public PurchaseCounterPK(Integer customerId, Integer purchaseId) {
            this.customerId = customerId;
            this.purchaseId = purchaseId;
        }


        public Integer getCustomerId() {
            return customerId;
        }

        public void setCustomerId(Integer customerId) {
            this.customerId = customerId;
        }

        public Integer getPurchaseId() {
            return purchaseId;
        }

        public void setPurchaseId(Integer purchaseId) {
            this.purchaseId = purchaseId;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            PurchaseCounterPK that = (PurchaseCounterPK) o;

            if (customerId != null ? !customerId.equals(that.customerId) : that.customerId != null) return false;
            if (purchaseId != null ? !purchaseId.equals(that.purchaseId) : that.purchaseId != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = customerId != null ? customerId.hashCode() : 0;
            result = 31 * result + (purchaseId != null ? purchaseId.hashCode() : 0);
            return result;
        }
    }


    Integer customerId;
    Integer purchaseId;
    Integer count = 0;

    @Id
    @Column(name = "customer_id")
    public Integer getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }

    @Id
    @Column(name = "purchase_id")
    public Integer getPurchaseId() {
        return purchaseId;
    }

    public void setPurchaseId(Integer purchaseId) {
        this.purchaseId = purchaseId;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }
}

当我使用Criteria进行查询并使用purchaseId和customerId作为Restriction.eq过滤器时,这就是生成的查询:

select this_.customerId as customerId137_0_, this_.purchaseId as purchaseId137_0_, this_.count as count137_0_ from customer_purchases_counter this_ where this_.purchaseId=? and this_.customerId=?

当然是错误的,因为字段customerId和purchaseId没有重命名为我使用@Column指定的名称????

2 个答案:

答案 0 :(得分:1)

映射似乎是正确的。这可能是HHH-4256的发生( Hibernate不使用IdClass 来表示@Column(name = ...)注释)。如果是这样,那么更新到更新版本的Hibernate会提供解决方案。

另外,根据@Column中使用IdClass注释的错误报告是解决方法。

答案 1 :(得分:-1)

我不确定我是否理解正确,但@Column只指定要映射到java数据的列。

所以你不应该将@Column注释应用于你的getter,而应该应用于你的变量声明。

@ID
@Column (name="customer_Id")
Integer customerId;
@ID
@Column (name="purchase_Id")
Integer purchaseId;