Есть бд, в ней 2 сущности и связь many to many, создаю DAO для crud операций, далее возникает вопрос, я хочу создать developer и добавить ему skill. Как мне добавить данные в таблицу skills_developers.
/*Create table developers*/
CREATE TABLE developers (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(100) NOT NULL
salary VARCHAR(100) NOT NULL
);
/*Create table skills*/
CREATE TABLE skills (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
/*Create table skill_developers with links*/
CREATE TABLE skills_developers (
dev_id INT NOT NULL,
sk_id INT NOT NULL,
FOREIGN KEY (dev_id) REFERENCES developers (id),
FOREIGN KEY (sk_id) REFERENCES skills (id)
);
public void addDevSkills(long id, long skillID) {
List<Long> skillsID = new ArrayList<>();
Statement statement = null;
String sql1 = "SELECT * FROM skills";
String sql2 = "INSERT INTO skills_developers VALUES (?,?)";
try (Connection connection = ApplicationJDBC.getConnection()) {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql1);
while (rs.next()) {
long i = rs.getLong("id");
if (skillsID != null) {
skillsID.add(i);
}
}
PreparedStatement preparedStatement = connection.prepareStatement(sql2);
Developer developer = new Developer();
for (Long sk_id : skillsID) {
if (sk_id == skillID) {
preparedStatement.setLong(1, developer.getId());
preparedStatement.setLong(2, sk_id);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}