How to force @JoinColumn columnDefinition to ignore referenced columnDefinition

166 views Asked by At

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.

1

There are 1 answers

2
rahulP On

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.