javaactivejdbc

activejdbc association between 2 models


I'm have a database with the following 2 tables.

Table 1

CREATE TABLE players ( id INT AUTO_INCREMENT, firstName VARCHAR(255), lastName VARCHAR(255), birthDate DATE, position VARCHAR(255), id_teams INT, PRIMARY KEY (id), FOREIGN KEY (id_teams) REFERENCES teams(id) );

Table 2

CREATE TABLE teams ( id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id) );

I also have the models Team and Player extending Model in my java project. I can add teams and players to the database but I don't understand how to add a player to a team without inserting the foreign key manually.

I've tried something like :

teams.get(0).addPlayer("Thomas", "Miller", new Date(2020, 0, 7), "Forward");

but that gives me the error

No association from model 'class sportstats.domain.Team' to model 'class sportstats.domain.Player'.

Any tips how I can think about this?


Solution

  • Please, see ActiveJDBC documentation here: https://javalite.io/one_to_many_associations

    The column players.id_teams should be called players.team_id, then it will work.