spring - 在 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有可能吗?任何人都可以帮忙吗?提前致谢!!!!
解决方案
您可以使用@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;
}
}
如需进一步阅读,请点击以下链接
推荐阅读
- javascript - 如何使 HTML 中 div 元素的 innerText 根据文本的长度自动调整大小?
- json - Apache2没有写入文件的权限[Errno 13] Permission denied Flask Python
- bixby - 我可以创建一个胶囊,向 Bixby 用户提供 COVID-19 信息吗?
- r - 在 emmip 图中更改线条粗细
- c++ - “Illegal else without matching if”错误消息c ++
- c# - 在 .NET 对象上设置“可为空”属性
- unix - 从 vivado 中的日志文件解析的两个时间戳之间的差异
- mysql - Laravel 使用多个数据库(2 MySQL,1 SQLite)
- javascript - 无法从 React 中的猫鼬映射数组
- python - Django:使用 django_table2 导出 csv 文件