I have the following OneToOne relational setting between two objects: ChecklistItem and ButtonAction (shown in the code snippets below). This seems to be a kind of unique setting. This is a bidirectional but optional ChecklistItem, and ButtonAction is the owner, which saves the ChecklistItem foreign key as the primary key.
ChecklistItem Class:
@Entity
@Table(name = "CHECKLIST_ITEM", schema = "CHKL_APP")
public class ChecklistItem implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CHECKLIST_ITEM_ID_SEQ")
@SequenceGenerator(name = "CHECKLIST_ITEM_ID_SEQ", sequenceName = "CHKL_APP.CHECKLIST_ITEM_ID_SEQ")
private Long id;
@OneToOne(optional = true, mappedBy = "checklistItem", cascade = CascadeType.ALL)
private ButtonAction button;
}
ButtonAction Class:
@Entity
@Table(name = "ACTION_BUTTON", schema = "CHKL_APP")
public class ButtonAction implements Serializable {
@Id
@Column(name = "checklist_item_id", unique = true, nullable = false, insertable = true, updatable = false)
@GenericGenerator(name = "generate-from-checklist-item", strategy = "foreign", parameters = @Parameter(name = "property", value = "checklistItem"))
@GeneratedValue(generator = "generate-from-checklist-item")
private Long checklistItemId;
@OneToOne
@PrimaryKeyJoinColumn
@JsonIgnore
private ChecklistItem checklistItem;
}
I use SpringBoot, so I have a ChecklistItemRepository interface extending SpringBoot CrudRepository:
public interface ChecklistItemRepository extends CrudRepository<ChecklistItem, Long> {}
In my ChecklistItem service, I configured the save method this way:
@Service
@Transactional
public class ChecklistItemServiceImpl implements ChecklistItemService {
@Override
public ChecklistItem saveChecklistItem(ChecklistItem checklistItem) {
processButtonAction(checklistItem);
return checklistItemRepository.save(checklistItem);
}
private void processButtonAction(ChecklistItem checklistItem,String username) {
ButtonAction button = checklistItem.getButton();
if(button != null) {
button.setChecklistItem(checklistItem);
if(checklistItem.getId() != null){
button.setChecklistItemId(checklistItem.getId());
}
}
}
}
, ChecklistItem ( POST PUT), ButtonAction ( ) ChecklistItem ( null) save.
... ChecklistItem NEW ButtonAction ( POSTed ButtonAction), :
org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.me.chklapp.checklistitem.action.ButtonAction.checklistItem];
nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.me.chklapp.checklistitem.action.ButtonAction.checklistItem]
"", , , , . , , , . , - , , , ; .
, , , , , cheklistitem. , Hibernate , , . , ButtonAction, ?
!