【问题标题】:JAVA Inserting into multiple tables with multiple rows depending on earlier IDJAVA根据早期ID插入具有多行的多个表
【发布时间】:2018-06-22 18:41:43
【问题描述】:

我正在尝试创建一些东西,我可以在其中将锻炼插入到数据库中,其中包含在该锻炼中完成的练习。问题是我想同时创建它们并存储我使用链接表的练习。

此表名为 Workout_Excercise,因此我可以在每次锻炼时存储多个练习。

问题是希望能够同时创建这些,但锻炼锻炼需要尚未创建的锻炼ID。

我当前的代码插入了锻炼效果很好,现在我很好奇我如何能够插入练习。

用于插入锻炼的当前代码:

正面

        $(".insertWorkout").on("click", function(){
            if(localStorage.getItem('token') != null ) {
                var token = localStorage.getItem('token');
             }
             else {
                 var token = null;
             }
        $.ajax({
             url: '/project/restservices/workouts/insert',
             type: 'POST',
             beforeSend:  function(xhr){
                 xhr.setRequestHeader('Authorization', 'Bearer ' + token);
             },
             data: {
                 titel: $(".workoutTitel").val() ,
                 beschrijving: $(".workoutBeschrijving").val(),
                 categorie_id: $(".categorieSelect").val(),
                 persoon_id: 1
             },
             success: function(response) {
                 if(response){
                     $(".workoutTitel").val("");
                     $(".workoutBeschrijving").val("");
                     $(".messageSpanSucces").html("Oefening invoeren gelukt");
                 }
                 else {
                     $(".messageSpanFail").html("Oefening invoeren mislukt");
                 }
             }
         });
    });

锻炼资源

    @Path("insert")
@POST
@Produces("application/json")
@RolesAllowed("user")
public Response saveWorkout(@FormParam("titel") String titel, @FormParam("beschrijving") String beschrijving,
        @FormParam("categorie_id") int categorie_id, @FormParam("persoon_id") int persoon_id) throws SQLException {
    WorkoutService service = ServiceProvider.getWorkoutService();
    boolean country = service.saveWorkout(titel, beschrijving, categorie_id, persoon_id);

    return Response.ok(country).build();
}

锻炼服务

    public boolean saveWorkout(String titel, String beschrijving, int categorie_id, int persoon_id) throws SQLException {
    return WorkoutPostgresDao.saveWorkout(titel, beschrijving, categorie_id, persoon_id);
}

锻炼DAO

    public boolean saveWorkout(String titel, String beschrijving, int categorie_id, int persoon_id) throws SQLException {
    boolean result = false;
    try (Connection con = super.getConnection()) {
        String query = "INSERT INTO \"Workout\" VALUES(?,?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(query);
        pstmt.setString(1, titel);
        pstmt.setString(2, beschrijving);
        pstmt.setInt(3, persoon_id);
        pstmt.setInt(4, categorie_id);
        pstmt.executeUpdate();
        result = true;

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
    return result;
}

【问题讨论】:

  • 你没有锻炼的实体吗?
  • 锻炼ID是主键吗??
  • 我确实有一个可以锻炼的实体!这包含标题和描述和东西。但该表是一个链接表,因此锻炼可以有多个练习。也是的,锻炼 ID 是主键

标签: java sql postgresql insert dao


【解决方案1】:

您可以使用以下方法来获取生成的密钥:

try (Connection con = super.getConnection()) {
        String query = "INSERT INTO \"Workout\" VALUES(?,?,?,?)";
        String query2 = "INSERT INTO Workout_exercise ... ";
        PreparedStatement pstmt = con.prepareStatement(query,PreparedStatement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, titel);
        pstmt.setString(2, beschrijving);
        pstmt.setInt(3, persoon_id);
        pstmt.setInt(4, categorie_id);
        pstmt.executeUpdate();
        result = true;

        try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs != null && rs.next()) {
                        workout_pkey = rs.getInt(1);
                        PreparedStatement pstmt2=con.prepareStatement(query2);
                        ...

                        for (Workout_exercise ex: exs) {
                              pstmt2.setInt(1, workout_pkey);
                              ...

                              pstmt2.addBatch();
                        }
                         pstmt2.executeBatch();

           }
       }    
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }

【讨论】:

  • 这看起来很有趣,但是如果我想一次插入多个 excersises 怎么办?
  • 我明白了,我可以发送一个包含所有 excersises 的 javascript 数组然后批量插入吗?非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
相关资源
最近更新 更多