首页 > 解决方案 > 在 JPA 中定义自定义 ID

问题描述

我是春季 JPA 的新手。我的要求是有一个复合列的 ID。我有一个分类帐表,其中有两列 log_id 和 order_id。我必须为相同的 order_id 插入多条记录,但我希望 log_id 每次只有在相同的 order_id 到来时才会增加。

喜欢:

order_id        log_id
--------         -----
1234              1
1234              2
1234              3
1235              1

春季JPA有可能吗?任何人都可以帮忙吗?提前致谢!!!!

标签: springspring-bootspring-data-jpa

解决方案


您可以使用@IdClass 和@GeneratedValue 实现此目的。

代码示例:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;

@Entity
@Table(name="LEDGER")
@IdClass( PK.class )
public class Ledger {

    @Id
    @Column(name = "log_id")
    @GeneratedValue
    public int logId;

    @Id
    @Column(name = "order_id")
    public int orderId;

    public String otherFields;
}

标识类

import java.io.Serializable;

public class PK implements Serializable{
    public int logId;
    public int orderId;

    public PK() {

    }

    public PK(int logId, int orderId) {
        super();
        this.logId = logId;
        this.orderId = orderId;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + logId;
        result = prime * result + orderId;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        PK other = (PK) obj;
        if (logId != other.logId)
            return false;
        if (orderId != other.orderId)
            return false;
        return true;
    }

}

如需进一步阅读,请点击以下链接

  1. 生成值
  2. 例子

推荐阅读