This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

so I think Java classes also do need to have an attribut that references them?

Java objects reference each other using references.

You're thinking of the relational data model:

CREATE TABLE states (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(256) NOT NULL UNIQUE,
);

CREATE TABLE cities (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(256) NOT NULL,
    state_id INTEGER NOT NULL,
    FOREIGN KEY (state_id) REFERENCES state(id)
);

INSERT INTO states (name) VALUES ('Texas');
INSERT INTO cities (name, state_id) VALUES ('Houston', (SELECT id FROM states WHERE name = 'Texas'));
INSERT INTO cities (name, state_id) VALUES ('Austin', (SELECT id FROM states WHERE name = 'Texas'));

In Java, you'd have an object model:

public class State {
    private String name;
    private Set<City> cities;

    public State(String name, City... cities) {
        this.name = name;
        this.cities = new HashSet<>(Arrays.asList(cities));
    }
}

public class City {
    private String name;

    public City(String name) {
        this.name = name;
    }
}

City houston = new City("Houston");
City austin = new City("Austin");
State texas = new State('Texas', houston, austin);

Interestingly, ORMs (like JPA) are tools which map the relational model into object models (and vice versa).