我需要在我的 spring boot webapp 中执行数据库插入。到目前为止,我所拥有的是一份体育比赛列表以及相应的信息。
一场比赛可以在同一天的不同时间举行。 让我烦恼的第一件事是我如何存储这个时间是数据库。这里需要一张新 table 吗? (我创建了一个日期表)
找了一圈还是没搞清楚怎么把 比赛信息及其日期同时出现在我的插入功能中。
我的插入功能需要一些工作,我需要一些帮助。
这个answer很好,但是没有达到我的要求
我的数据库架构:
CREATE TABLE competition (
competition_id integer PRIMARY KEY,
nom varchar(128) NOT NULL,
);
CREATE TABLE date (
id integer PRIMARY KEY,
date_time timestamptz,
competition_id integer REFERENCES competition (competition_id)
);
Json数据:
{
"id": "420",
"name": "SOCCER",
"dates": [
"2016-05-12T03:00:00.000Z"
"2016-05-12T04:00:00.000Z"
"2016-05-12T05:00:00.000Z"
]
},
{
"id": "220",
"name": "BASKETBALL",
"dates": [
"2016-05-12T03:00:00.000Z"
"2016-05-12T04:00:00.000Z"
]
}
我的比赛类(class):
public class Competition{
private int id;
private String name;
private String[] dates;
// setters ... getters
}
插入数据的函数:
private static final String INSERT_STMT =
" insert into competition (id, name)"
+ " values (?, ?)"
;
public int insert(Competition competition) {
return jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(INSERT_STMT);
ps.setInt(1, competition.getId());
ps.setString(2, competition.getName());
return ps;
});
// insert also in date table ???
}
最佳答案
首先,如果您需要数据一致性,那么您应该用事务包装您的插入语句。要将数据插入多个表,您应该执行多个插入语句,就像您使用 sql 一样。如果您需要返回更新的行数,您可以创建包装类,您可以在其中存储并返回它。
关于java - 在一个函数中使用 JDBC 将数据插入到多个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44446094/