javaplayframeworkcascadeebean

Multiple levels of cascading persists in Ebean


I have a model class which defines a list of children that are models of the same class. Persisting a new object with some initial children works fine, but when I have two or more levels of children Ebean does not seem to be able to handle it well. This seemed unexpected so I'm worried I made a mistake. At the same time I couldn't find any examples or mentions about multiple level persist cascades so my questions are: Is there an error in my code, Is this even a supported feature or did I find a bug?

My model class:

@Entity
public class TestEntity extends Model {
    @Id
    private int id;
    private String text;
    @ManyToOne
    private TestEntity parentEntity;
    @OneToMany(cascade = CascadeType.ALL)
    private List<TestEntity> childEntities;
...
}

My program:


TestEntity grandparent = new TestEntity();
grandparent.setText("grandparent");
TestEntity parent = new TestEntity();
parent.setText("parent");
TestEntity child = new TestEntity();
child.setText("child");
grandparent.setChildEntities(Collections.singletonList(parent));
parent.setChildEntities(Collections.singletonList(child));
grandparent.save();

I added logging for the sql statements and it is evident that the third insert didn't get the correct value for parent_entity_id. That row fails due to 0 not being a valid foreign key and the batch is reverted.

insert into test_entity (text, parent_entity_id) values ('grandparent',null);
insert into test_entity (text, parent_entity_id) values ('parent',1);
insert into test_entity (text, parent_entity_id) values ('child',0);

I'm using Play framework 2.7.3 with the ebean plugin version 5.0.2 and Ebean version 11.39


Solution

  • This is indeed a supported feature and the code snippet above is expected to persist all three entities. There was a unit test added to verify that this is working correctly in the latest version of ebean.

    In ebean 11.39 which is currently the latest supported by play framework the test fails. An easy workaround when using that version is to use Long instead of primitive int as ID for the models.

    While not an answer to this specific question, it is good to be aware that these same symptoms also appear if the collections are set without using setters enhanced by ebean. I had some trouble using public fields and play enhancer .