我需要具有客户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"
}
]
答案 0 :(得分:1)
您应该创建一个复合键来正确处理您的数据。首先,创建另一个代表键的类:
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;
}
最好在hashCode
类中实现equals
和ClientPK
方法。