I'm writing an Entity with a PK with two attributes: a Long FK to another Entity, and an auto incrementing Long. I followed the suggestions of this article.
Here's my IdClass and Entity. The autoincrementing attribute should be 'id'.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomPosologyId implements Serializable {
private Long id;
private Long planId;
}
@Entity
@NoArgsConstructor
@IdClass(CustomPosologyId.class)
@Table(name = "custom_posology")
public class CustomPosology {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@Getter @Setter
private Long id;
@Id
@Column(name = "plan_id")
@Getter @Setter
private Long planId;
@ManyToOne
@JoinColumn(name = "plan_id", referencedColumnName = "id", insertable = false, updatable = false)
@Getter @Setter
private DrugPlan drugPlan;
@Column(name = "date_time", nullable = false)
@Getter @Setter
LocalDateTime dateTime;
public CustomPosology(CustomPosologyForm form){
this.dateTime = form.getDateTime();
}
}
Here's the problem: When I try to run a save operation on 'CustomPosology' with 'planId' already properly set, I get the following below. It seems to be related to the framework not being able to find the attribute setter:
2023-04-05 18:00:04.645 ERROR 2433 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.campera.app3idadefacil.model.CustomPosologyId.id] setter of com.campera.app3idadefacil.model.CustomPosologyId.id; nested exception is org.hibernate.PropertyAccessException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.campera.app3idadefacil.model.CustomPosologyId.id] setter of com.campera.app3idadefacil.model.CustomPosologyId.id] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Long field com.campera.app3idadefacil.model.CustomPosologyId.id to org.hibernate.id.IdentifierGeneratorHelper$2
Thanks in advance for the help!
I previously tried writing the composite key as an @Embeddable but it turns out that @GeneratedValue won't work if not followed by @Id, as pointed out in the article I mentioned.
I have seen some stack overflow questions where users answered that it is not possible to have a composite key with incrementing value, however the article says otherwise.
I have also tried removing Lombok usage in these classes but it didn't help.