完整性约束违规:唯一约束或索引违规 HSQLDB

Integrity constraint violation: unique constraint or index violation HSQLDB

例如,如果我添加 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;
        }

你想在这里更新:

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