0

I want to share primary key using one-to-one relation.

and when parents are persisted, their children also be persisted (CascadeType.ALL)

this is my code

@Entity
@Table(name = "TB_PAR")
@Data
public class Par implements Serializable {
    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "ID", referencedColumnName = "ID")
    private Child child;
}


@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "TB_CHILD")
public class Child implements Serializable {

    @Id
    @OneToOne
    @JoinColumn(name = "ID", referencedColumnName = "ID")
    private Par par;
}
//Session initialize
...
PAR par = new PAR();
Child child = new child();
par.setChild(child);
session.persist(par);
...

then, print a warning that a null value cannot be inserted into the id column.

(depend on rdbms / my db is oracle so I can see ORA-01400)

how can i fix it?

HelloRacoon
  • 87
  • 1
  • 9
  • You can use the answer in this question.You need @MapsId annotations which will map pk of one table as pk and also fk to another table.https://stackoverflow.com/questions/59282221/hibernate-map-id-automatically-from-field/59440796#59440796 – user06062019 Dec 31 '19 at 06:47

2 Answers2

0

Can you try with nullable=false

 @JoinColumn(name = "ID", referencedColumnName = "ID", nullable=false)
Mak
  • 1,068
  • 8
  • 19
0

You could try a "derived identity" and your code would look like this:

@Entity
@Table(name = "TB_PAR")
@Data
public class Par implements Serializable {
    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;

    @OneToOne(mappedBy = "par", cascade = CascadeType.ALL)
    private Child child;
}


@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "TB_CHILD")
public class Child implements Serializable {

    @Id
    @Column(name = "ID")
    private UUID id;

    @OneToOne
    @MapsId
    private Par par;
}

Derived identities are discussed (with examples) in the JPA 2.2 spec in section 2.4.1.

Brian Vosburgh
  • 3,146
  • 1
  • 18
  • 18