0

I have following code for self-referencing entity

@Data
@Builder
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class Dictionary implements Persistable<Long> {

    @Id
    @GeneratedValue(generator = "dictionary_gen", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "dictionary_gen", sequenceName = "dictionary_item_key_seq", allocationSize = 1)
    @Column(name = "item_key", unique = true, updatable = false, columnDefinition = "serial")
    private Long itemKey;

    @Override
    @JsonIgnore
    public Long getId() {
        return itemKey;
    }

    @Override
    @JsonIgnore
    public boolean isNew() {
        return itemKey == null;
    }

    @Nullable
    @ManyToOne
    @JoinColumn(name = "parent_item_key", columnDefinition = "",
            foreignKey = @ForeignKey(name = "dictionary_item_key_fk", value = ConstraintMode.NO_CONSTRAINT))
    @JsonIgnore
    private Dictionary parent;

    @JsonProperty("parentItemKey")
    public Long getParentItemKey() {
        return parent.getItemKey();
    }

    @Column(name = "item_name", length = 120, nullable = false)
    private String itemName;

    @Column(name = "item_description", length = 120, nullable = false)
    private String itemDescription;
}

it's generated following DDL

create table dictionary (item_key serial not null, 
 item_description varchar(120) not null, 
 item_name varchar(120) not null, 
 parent_item_key serial, 
 primary key (item_key))

As You can see the the serial column definition translated from the item_key column to the parent_item_key. How it's possible to define parent_item_key not as serial? I would like to keep it nullable if my dictionary item do not have parent. I have tried to use @AssociationOverride but it was not helpful as well.

cane
  • 892
  • 1
  • 10
  • 16
  • I see only only one option how to achieve it - avoid self-relation. But Im not sure if it correct way. @Nullable @Column(name = "parent_item_key") @JsonProperty("parentItemKey") private Long parentItemKey; – cane Aug 10 '23 at 07:50

1 Answers1

0

I think you can use it like this.

@ManyToOne(optional = true)
private Dictionary parent;

(Optional) Whether the association is optional. If set to false then a non-null relationship must always exist.

rahulP
  • 244
  • 2
  • 6
  • ManyToOne is optional by default. is not enough – cane Aug 16 '23 at 11:15
  • I think your problem is exactly the same as this one. https://stackoverflow.com/questions/15511899/cannot-make-manytoone-relationship-nullable – rahulP Aug 16 '23 at 12:51