How to create composite primary key with one auto generated value?

5k Views Asked by At
I am trying to map entity with my existing database table which is having two primary keys.

Out of two keys, one primary key is auto generated.

I am using `Spring Boot`, `JPA`, `Hibernate` and `MySQL`. I have used `@IdClass` to map with the composite primary class (with public constructor, setter/getters, same property names, equals and hash code methods).

`org.springframework.data.repository.CrudRepository` save method to save the entity.  

Code snippet below.

@Entity
@Table(name = "data")
@IdClass(DataKey.class)
public class DeviceData {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private BigInteger id;
    @Column(name="name")
    private String name;
    @Id
    @Column(name="device_id")
    private int deviceId;
    getters/setters
}
public class DataKey implements Serializable {
    private static final long serialVersionUID = 1L;
    private BigInteger id;
    private int deviceId;
    //setter/getters
    public DataKey() {
    }
    public DataKey(BigInteger id, int deviceId) {
        this.id = id;
        this.deviceId = deviceId;
    }
    public int hashCode() {
        return Objects.hash(id, deviceId);
    }
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof DataKey))
            return false;
        DataKey dk = (DataKey) obj;
        return dk.id.equals(this.id) && dk.deviceId == (this.deviceId);}
}
I am using org.springframework.data.repository.CrudRepository save method for persisting the entity.

DeviceData data=new DeviceData();

data.setName("device1"); data.setDeviceId("1123");

dao.save(data); //dao extending crudrepository interface.

But I am getting below errors :

    org.springframework.orm.jpa.JpaSystemException: Could not set field 
    value [POST_INSERT_INDICATOR] value by reflection.[class DataKey.id]
    setter of DataKey.id; nested exception is
    org.hibernate.PropertyAccessException: Could not set field value
    [POST_INSERT_INDICATOR] value by reflection : [class class DataKey.id]
    setter of class DataKey.id.

Caused by: java.lang.IllegalArgumentException: Can not set java.math.BigInteger field DataKey.id to org.hibernate.id.IdentifierGeneratorHelper$2

3

There are 3 best solutions below

5
codeLover On

I had also tried the same in one of my projects but eventually I found out that it is not possible to auto generate one of the key attributes(in case of composite primary key) in JPA. So, I did it separately by invoking the sequence with the help of query.

1
Pooja Garg On
I have achieved this by creating a one orderId class with parameters -- Mysql
@Getter
@Setter
public class OrderId implements Serializable {

    private int oId;
    private int customerId;
    private int productId;

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        OrderId orderId = (OrderId) o;
        return oId == orderId.oId && customerId == orderId.customerId && productId == orderId.productId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(oId, customerId, productId);

    }

the class OrderData with orderid as auto generated field in mysql
@Entity
@Table(name = "OrderData")
@Getter
@Setter
@NoArgsConstructor
@IdClass(OrderId.class)
public class OrderData{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int oId;
    @Id
    private int customerId;
    @Id
    private int productId;
    private int quanity;
    private String paymentMode;
    private String orderStatus;

}
0
RedTailedHawk On

I was able to solve it using a sequence generator.

    @Id
    @SequenceGenerator(name="my_seq", sequenceName="my_db_table_seq", allocationSize=1)
    @GeneratedValue(generator = "my_seq")
    @Column(name = "id", updatable = false, nullable = false)
    private BigInteger id

In my case I'm using Postgres, and my tables that have SERIAL as a column data type also have a corresponding entry in the pg_catalog.pg_sequences table (e.g. my_db_table_seq in my example above).

If you don't specify a particular named sequence generator (and just use @GeneratedValue(strategy = GenerationType.SEQUENCE) on your @Id column), it looks like Hibernate defaults to one called hibernate_sequence, and I have seen some suggestions to run the db command CREATE SEQUENCE hibernate_sequence START 1 to get that created in the database. But this would use the same sequence for every table that inserts rows via Hibernate, so probably not a good idea. Best to use the sequence that gets created in the database for that table and then be explicit with the @SequenceGenerator annotation.

There does seem to be a problem using @GeneratedValue(strategy = GenerationType.IDENTITY) in a composite key on an entity that has @IdClass, so would be nice if Hibernate could support this.

But looks like the sequence generator is a valid workaround, so that's what I'm going with.