Search code examples
javahibernatejpaspring-datajavax

Java Persistence Composite ID


I'm trying to insert a record with composite primary key, but at the time of saving a new record I get this message:

e = (org.springframework.orm.jpa.JpaSystemException) org.springframework.orm.jpa.JpaSystemException: Could not set field value [POST_INSERT_INDICATOR] value by reflection...

@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "produto")
@IdClass(ProdutoId.class)
public class Produto implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_produto")
    private Long idProduto;

    @Id
    @Column(name = "oficina", insertable = false, updatable = false)
    private Long idOficina;

    @ManyToOne
    @JoinColumn(name = "oficina")
    private Oficina oficina;

}



@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Data
public class ProdutoId implements Serializable {

    public Long idProduto;
    public Long idOficina;

}


@Repository
public interface ProdutoRepository extends JpaRepository<Produto, ProdutoId> {}

Has anyone ever seen a bug like this?


Solution

  • To create composite primary key you can refer this example,

    @Entity
    @Table(name="testuserrole")
    public class UserRole{
        @EmbeddedId
        private UserRoleId id = new UserRoleId();
    
        public UserRoleId getId() {
            return id;
        }
    
        public void setId(UserRoleId id) {
            this.id = id;
        }
    
        @Transient
        public long getUserId() {
            return id.userId;
        }
    
        public void setUserId(long userId) {
            id.userId=userId;
        }
    
        @Transient
        public long getRoleId() {
            return id.roleId;
        }
    
        public void setRoleId(long roleId) {
            id.roleId=roleId;
        }
    
    }
    
    @Embeddable
    class UserRoleId implements Serializable {
    
        @Column(name = "user_id")
        public long userId;
    
        @Column(name = "role_id")
        public long roleId;
    
    }