I am using hibernate version 5.2.4 and postgresql v 9.4 and trying a create an annotated class which will help me build a table as below:
ID | client_name | company_name | email
---+-------------+----------------------------
1 | bob | smith's |
2 | mark | JK warehouse |
Where in 'ID' should be auto-incremented value and a composite key with client_name and company_name. The composite keys are not referencing from any table.
I was able to achieve this partially with @EmbeddedId and the @Embeddable as follows:
@Embeddable
public class ClientId implements Serializable {
@Column(name = "client_name")
private String clientName;
@Column(name = "company_name")
private String companyName;
....
}
@Entity(name = "ClientDetails")
@Table(name = "clientdetails")
public class ClientDetails {
@EmbeddedId
private ClientId id;
private String email;
...}
Which results in table as follows:
Column | Type | Modifiers | Storage
--------------+------------------------+-----------+----------
client_name | character varying(255) | not null | extended
company_name | character varying(255) | not null | extended
email | character varying(255) | | extended
but not able to incorporate the auto increment ID column. Also I tried using @Idclass and was not successful. I tried to google and found other scenario where the requirement was either to contain the Id within embeddable class or had reference to other tables, so finally decided to post here for help.
Many thanks.
Update: I managed to create a composite key using @IdClass and an Id with @GeneratedValue as follows:
@Entity
@Table(name = "clientdetails")
@IdClass(ClientId.class)
public class ClientDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Id
@Column (name="client_name")
private String clientName;
@Id
@Column (name="company_name")
private String companyName;
@Column (name="client_email")
private String email;
....
}
client_name | company_name | id | client_email
-------------+--------------+----+-----------------
bob | smith's | | abc@xyz.com
mark | JK warehouse | | abc@xyz.com
(2 rows)
But this does not auto populate values for Id, please help