我需要一个包含客户端 ID、该 ID 的客户端(客户端)和客户端名称的客户端列表。问题是该表来自没有 PK 的 dblink
@Entity
@Table(name = "mytable", schema = "myschema")
public class Client {
@Column(name = "clientid")
@Id
private Integer clientid;
@Column(name = "client")
private Integer client;
@Column(name = "name")
private String name;
}
使用这段代码,我会一遍又一遍地重复名字,直到列表末尾,因为没有 PK,如果没有 PK,我无法启动应用程序。当我将 client 列设置为 PK 时,会发生类似的情况(我正确获取所有名称,但 clientid 字段显示错误的值。是否有解决方法?
示例数据:
数据错误(将clientid设置为@Id时):
[
{
"clientid": 99,
"client": 81,
"name": "Organization 1"
},
{
"clientid": 99,
"client": 81,
"name": "Organization 1"
},
{
"clientid": 99,
"client": 81,
"name": "Organization 1"
}
]
数据错误(将客户端设置为@Id时):
[
{
"clientid": 99,
"client": 81,
"name": "Organization 1"
},
{
"clientid": 3,
"client": 99,
"name": "Organization 2"
},
{
"clientid": 3,
"client": 127,
"name": "Organization 3"
}
]
我应该得到什么:(clientid 在所有情况下都是正确的)
[
{
"clientid": 99,
"client": 81,
"name": "Organization 1"
},
{
"clientid": 3,
"client": 99,
"name": "Organization 2"
},
{
"clientid": 1,
"client": 127,
"name": "Organization 3"
}
]
最佳答案
您应该创建一个复合键来正确处理您的数据。首先,创建另一个代表 key 的类:
public class ClientPK implements Serializable{
private static final long serialVersionUID = 1L;
private Integer clientid;
private Integer client;
/*Constructor, getters and setters here*/
}
然后更新类Client
,如下所示:
@Entity
@Table(name = "mytable", schema = "myschema")
@IdClass(ClientPK.class)
public class Client {
@Column(name = "clientid")
@Id
private Integer clientid;
@Column(name = "client")
private Integer client;
@Column(name = "name")
private String name;
}
最好在ClientPK
类中实现hashCode
和equals
方法。
关于java - 对于没有 PK 的表,使用 JPA 组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53949084/