![](/img/trans.png)
[英]JPA : one table with primary key and another table with primary and foreign key
[英]Java/Mysql Selecting Primary Key values from one table and Insert them to another table as Foreign Keys
我正在使用 Netbeans 中的 Swing 创建一个 Java 汽车管理应用程序,作为数据库,我使用的是 Mysql,它将执行所有 CRUD 操作。 我创建了一个包含 3 个不同表的数据库。
数据库架构
CREATE TABLE car_make(
make_id INT NOT NULL AUTO_INCREMENT
make VARCHAR(50)
PRIMARY KEY(make_id)
)
CREATE TABLE car_model(
model_id INT NOT NULL AUTO_INCREMENT
model VARCHAR(50)
fk_make_id INT
PRIMARY KEY(model_id)
FOREIGN KEY(fk_make_id) REFERENCES car_make(make_id)
)
CREATE TABLE car_attributes(
car_attr_id INT NOT NULL AUTO_INCREMENT
fk_make_id INT
fk_model_id INT
year INT
body_type VARCHAR(50)
mileage INT
price DECIMAL(6,2)
PRIMARY KEY(car_attr_id )
FOREIGN KEY(fk_make_id) REFERENCES car_make(make_id)
FOREIGN KEY(fk_model_id) REFERENCES car_model(model_id )
);
car_make
表已经填充了我手动插入的所有汽车品牌,并且它们的 ID 是自动生成的。 并且car_model
表还填充了每个品牌的不同型号。
我还使用 Java Swing 在 netbeans 中创建了用户界面,用户可以在其中选择汽车的品牌,这将自动生成相应的型号、年份、里程等,并将所有数据插入car_attribute
表中。 我的问题是,将汽车品牌和型号作为外键插入car_attribute
表的查询是什么。 例如,如果用户选择 Make-BMW 和 Model-5 系列,我想将这两个 IDS 插入到第三个表中。
这种情况下想出了当你要添加新的车,所以GUI显示您CAR_MAKEs当你选择,它会告诉你CAR_MODELs,那么你需要的ArrayList来存储提取的数据(car_makes OR car_models)的ID,并用它在用户提交时的查询
只是伪代码
int carMakesSelectedIndex = comboCarMakes.getSelectedIndex();
int carModelsSelectedIndex = comboCarModels.getSelectedIndex();
PreparedStatement stmt=con.prepareStatement("insert into car_attributes values(?,?,?,?,?,?,?,?,?,?)");
stmt.setInt(1,carAttribute);
stmt.setInt(2,carMakesIdList.get( carMakesSelectedIndex ) );
stmt.setInt(3,carMakesIdList.get( carModelsSelectedIndex ) );
stmt.setString(4,carYear );
// the same with other attribute
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.