【问题标题】:完整性约束违规:唯一约束或索引违规 HSQLDB
【发布时间】:2022-01-23 11:49:34
【问题描述】:

例如,如果我添加new Department(new BigInteger("50"), "ODD", "SPB"),所有工作,它的值都插入到数据库中。但是如果我想再次插入例如new Department(new BigInteger("50"), "ODDMOD", "SPBMOD"),则出现java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: unique constraint or index violation; SYS_PK_10092 table: DEPARTMENT。我知道不能插入具有相同主键的值,但是如果存在主键或其他解决方案如何更新值?

 public Department save(Department department) throws SQLException {
    
            Connection connection = ConnectionSource.instance().createConnection();
            String sql = "insert into department values (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);
    
            statement.setLong(1, Long.parseLong(String.valueOf(department.getId())));
            statement.setString(2, department.getName());
            statement.setString(3, department.getLocation());
                    statement.executeUpdate();
            PreparedStatement st = connection.prepareStatement("select * from department where id = ? ");
            st.setLong(1, Long.parseLong(String.valueOf(department.getId())));
            ResultSet resultSet = st.executeQuery();
            resultSet.next();
            Department demper = new Department(
                    new BigInteger(String.valueOf(resultSet.getInt("id"))),
                    resultSet.getString("name"),
                    resultSet.getString("location")
            );
            return demper;
        }

【问题讨论】:

    标签: java sql hsqldb


    【解决方案1】:

    你想在这里更新:

    public Department save(Department department) throws SQLException {
        Connection connection = ConnectionSource.instance().createConnection();
        String sql = "MERGE INTO department d1 " +
                     "USING (VALUES ?, ?, ?) d2 (id, name, location) " +
                     "    ON (d1.id = d2.id) " +
                     " WHEN MATCHED THEN UPDATE SET " +
                     " d1.name = d2.name, d1.location = d2.location " +
                     " WHEN NOT MATCHED THEN INSERT (id, name, location) VALUES (d2.id, d2.name, d2.location)";
        PreparedStatement statement = connection.prepareStatement(sql);
    
        // execute merge here as before
    
        statement.setLong(1, Long.parseLong(String.valueOf(department.getId())));
        statement.setString(2, department.getName());
        statement.setString(3, department.getLocation());
        statement.executeUpdate();
    
        // ...
    }
    

    如果部门id 不存在于表中,则MERGE 会执行插入操作。否则它将进行更新。请注意,如果您从纯 JDBC 转移到 JPA/Hibernate,JPA save() 方法可以在后台自动为您更新。

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 2015-11-03
      • 2014-11-29
      • 2013-11-27
      • 2018-06-28
      • 2020-04-22
      • 1970-01-01
      • 2015-05-07
      • 2016-11-22
      相关资源
      最近更新 更多