简体   繁体   中英

Composite key with JPA for a table with no PK

I need a list of clients with a client id, clients of this id (client), and client name. The issue is that this table comes from a dblink without a PK

@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;
}

With this code I'm getting the first name duplicated over and over till the end of the list, because theres no PK and I can't start the application without a PK. Something similar happens when I set the client column as PK (I get all the names correctly but the clientid field shows a wrong value. Is there a workaround for this?

Sample data:

Wrong data (when setting clientid as @Id):

[
  {
    "clientid": 99,
    "client": 81,
    "name": "Organization 1"
  },
  {
    "clientid": 99,
    "client": 81,
    "name": "Organization 1"
  },
  {
    "clientid": 99,
    "client": 81,
    "name": "Organization 1"
  }
]

Wrong data (when setting client as @Id) :

[
  {
    "clientid": 99,
    "client": 81,
    "name": "Organization 1"
  },
  {
    "clientid": 3,
    "client": 99,
    "name": "Organization 2"
  },
  {
    "clientid": 3,
    "client": 127,
    "name": "Organization 3"
  }
]

What I should get: (clientid is correct in all cases)

[
  {
    "clientid": 99,
    "client": 81,
    "name": "Organization 1"
  },
  {
    "clientid": 3,
    "client": 99,
    "name": "Organization 2"
  },
  {
    "clientid": 1,
    "client": 127,
    "name": "Organization 3"
  }
]

You should create a composite key to handle correctly your data. First, create another class that will represent the key:

public class ClientPK implements Serializable{

    private static final long serialVersionUID = 1L;

    private Integer clientid;

    private Integer client;

    /*Constructor, getters and setters here*/
}

And then update the class Client as it follows:

@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;
}

It is better to implement hashCode and equals method in ClientPK class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM