What's the best practice for compositions with cyclic references?

I prepared a demo project to address the requirement I was unable to implement.


This is a CUBA Platform sample application showing a quite popular use case of
using compositions in a domain model:

  • Entity Parent has multiple Child
  • One of the children is considered as a “default one” by using a link from Parent

Of course, it’s possible to use an attribute for Child to denote whether it’s
a default child or not, but this approach makes an integrity check for having only
one default child rather difficult.

The tricky moment is saving this composition for the first time when creating
because here we have something kind of cyclic references.

Now this does not work neither with ASSOCIATE link nor COMPOSITE link.
The error is: SQLIntegrityConstraintViolationException: integrity
constraint violation: NOT NULL check constraint; SYS_CT_10364 table:

1 Like

Hi Ilia,

You have to untie the entities on the database level and just make the Default Child field required in UI.

public class Parent extends StandardEntity {
    // ...

    @OneToOne(fetch = FetchType.LAZY/*, optional = false*/)
    @JoinColumn(name = "DEFAULT_CHILD_ID")
    protected Child defaultChild;

    // ...
<fieldGroup id="fieldGroup"
    <column width="250px">
        <field property="brief"/>
        <field optionsDatasource="childrenDs"

Also, the COMPOSITION relationship is not required for defaultChild attribute, as well as the defaultChildDs nested datasource.

Yep, this works, thank you. It looks as if setting DEFAULT_CHILD_ID as nullable is enough to get this worked.
You need not remove FKs, and that’s good.

alter table APP_PARENT alter column DEFAULT_CHILD_ID set null ;