Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Embedded Classes/DB structure

I'm trying to store my multi-tier menu in the database. I have a class HorizontalMenu which contains a List<MenuItem> for its items. My MenuItem class contains a String for the text, a String for the URL, and another HorizontalMenu for a sub-menu if it has one.

So my main menu can have any number of MenuItems, each of which can have zero or one HorizontalMenus.

So I'm wondering how exactly to set this up in code so it will be correctly set up in the DB.

I'm using Ebeans and Play Framework 2.0, so an answer in those terms would be great, but if somebody could just point me in the right direction in DB terms that would be fine too.



Here's what I've got so far:

HorizontalMenu.java:

@Entity
@Embeddable
public class HorizontalMenu extends Model{

    @Id
    @GeneratedValue
    public Long id;

    public List<MenuItem> items;

    public Long getId()
    {
        return this.id;
    }
    public void setId(Long id)
    {
        this.id = id;
    }

    public List<MenuItem> getItems()
    {
        return this.items;
    }
    public void setItems(List<MenuItem> items)
    {
        this.items = items;
    }

    public static Finder find = new Finder(Long.class, HorizontalMenu.class);
}

MenuItem.java:

@Entity
@Embeddable
public class MenuItem {
    @Id
    public Long id;
    public String text;
    public String url;
    public HorizontalMenu subMenu;
}

Upvotes: 0

Views: 457

Answers (1)

jsf
jsf

Reputation: 2981

Since your MenuItem class is @Embeddable. The data member items in the HorizontalMenu class would be @Embedded. So, here's how it should appear:

@Embedded
public List<MenuItem> items;

Since your MenuItem is marked as @Embeddable, you don't have to mark it as an @Entity. There are certain requirements for an Object to be an Entity e.g. Id. And Embeddable objects don't have a unique identity. So, don't bother.

To test this quickly create an in-memory database. Now, when you start your app - DB will be created on the fly. So, you would be able to see how the tables are laid out. The script that is executed is available in the conf directory.

For further testing - Insert some data during Application start-up via YAML (hint - look into GlobalSettings Object, example available in Play Docs) and see if it gets inserted correctly.

Upvotes: 1

Related Questions