Vidura Mudalige
Vidura Mudalige

Reputation: 812

What is the simplest way to create nested objects in Ebean?

I need two Ebean model classes called "States" and "Children". A "State" object can contain nested Child objects(List of children).

Here is the basic States class,

@Entity
public class States extends Model {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Constraints.Required(message = "stateName cannot be null")
    @Column(nullable = false)
    private String statename;

    @Column(nullable = true)
    private String url;

    @Column(nullable = true)
    private String parent;

    private List<Children> childrenList;
}

Here is the basic Children class,

@Entity
public class Children extends Model {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false)
    private String statename;

    @Column
    private String child;
}

What are the minimal modifications that should be done to these classes to create State objects using Ebean ORM? I went through the post,

Ebean Query by OneToMany Relationship

But there, a lot of changes have been suggested. I just want the minimal modifications.

Upvotes: 5

Views: 964

Answers (1)

Vidura Mudalige
Vidura Mudalige

Reputation: 812

All I had to do was, doing a small modification to the "States" class,

@Entity
public class States extends Model {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Constraints.Required(message = "stateName cannot be null")
    @Column(nullable = false)
    private String statename;

    @Column(nullable = true)
    private String url;

    @Column(nullable = true)
    private String parent;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Children> childrenList;
}

Only change I have done here is,

@OneToMany(cascade = CascadeType.ALL)

I did not do any changes to the "Children" class. Before starting the play app I set

play.evolutions.enabled = true

in "application.conf" file. Then using the evolution SQL file that was created in "evolution.default" folder, I adjusted the schema of the database. After that "States" objects were created successfully with nested "Children" objects.

Upvotes: 5

Related Questions