0

I'm trying to bind a table looks like this

some_id   BIGINT PK
parent_id BIGINT    NN '0'

As you can see,

  • It looks like a self-referencing entity
  • No FK for parent_id
  • parent_id is not nullable and defaults to 0

How can I bind?

Does following mapping just fine?

class Some {

    @Id
    private Long id;

    @ManyToOne // optional?
    @JoinColumn(name = "parent_id", referencedColumnName = "some_id")
    private Some parent;
}

How, in other words, can I map 0 to null?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

1

I think better to harden the existence of a root element by adding the root to the table:

INSERT INTO some (some_id, parent_id) VALUES (0, 0);
COMMIT;

This way, that entry with some_id = 0 will now serve as the root element, and make any references with parent_id = 0 a valid reference.

I do not think there is a way to map 0 to NULL - not with the way JPA works, not for reference id's.

YoYo
  • 9,157
  • 8
  • 57
  • 74