3

In my database I have a table which is show in below. Now I want to make a nested data structure to draw on a view by an algorithm to transfer data from table to this

Tables -> Seats -> Rounds -> Dish_names

Note that -> stands for 'contain'

Could anyone have a clean way to do this in Java. Thanks!

enter image description here

0

2 Answers 2

1

Not sure what you want exactly, but if you want a nested Java Object (entity) to correspond to the table, read on:

Since Tables contain Seats contain Rounds contain Dish_names, you start from the innermost entity (Dish):

Public class Dish{
  private int id; // an id  
  private String dish_name;
  // getters and setters
}

Your Rounds contain the Dishes

 Public class Round{
      private int id; // an id  
      private List<Dish> dishes;
      // getters and setters
    }

Your Seats contain the Rounds

Public class Seat{
      private int id; // an id  
      private List<Round> rounds;
      // getters and setters
    }

And finally you Tables contain the Seats

 Public class Table{
      private int id; //  
      private List<Seat> seats;
      // getters and setters
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that're entities, but I need to fill out the data from the table
0

The class structure as you mentioned.

class Table
    List<Seat> seats = ArrayList<>();

class Seat
    List<Round> rounds = ArrayList<>();

class Round
    List<Seat> seats = ArrayList<>();

class Dish

For instance, using immutable objects:

public class Table {
    public final int id;
    public final List<Seat> seats = ArrayList<>();

    public Table(int id) {
        this.id = id;
    }
}

For construction of unique entity objects you need to map the keys to the entity object.

Map<Integer, Table> tablesById = new HashMap<>();
Map<Integer, Seat> seatsById = new HashMap<>();
Map<Integer, Round> roundsById = new HashMap<>();
Map<String, Dish> dishesByName = new HashMap<>();

With a bit more effort, but cleaner result one could make Set<Table> etcetera.

Now you can traverse the database table and check

Table table = new Table(resultSet.getInt("Table"));
table = tablesById.putIfAbsent(table.id, table);
// Now table is a maybe already existing table of the map.

Seat seat = new Table(resultSet.getInt("Seat"));
seat = seatsById.putIfAbsent(seat.id, seat);
table.seats.add(seat);

...

The method putIfAbsent exists since java 8. In earlier java you can get and only when it does not exist put a new Table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.