Java + MySQL integrity violation handling

后端 未结 3 1160
日久生厌
日久生厌 2021-01-06 03:14

I write Java program using JDBC (mysql database). When I violate mysql integrity (f.e. I try to insert same primary key value) I catch SQL exception. Should

3条回答
  •  天涯浪人
    2021-01-06 03:59

    There are indeed basically two ways to achieve this:

    1. Test if record exists before inserting --inside the same transaction.

    2. Determine if SQLException#getSQLState() of the catched SQLException starts with 23 which is a constraint violation as per the SQL specification. It can namely be caused by more factors than "just" a constraint violation. You should not amend every SQLException as a constraint violation.

      public static boolean isConstraintViolation(SQLException e) {
          return e.getSQLState().startsWith("23");
      }
      

    I would opt for the first one as it is semantically more correct. It is in fact not an exceptional circumstance. You namely know that it is potentially going to happen. But it may potentially fail in heavy concurrent environment where transactions are not synchronized (either unawarely or to optimize performance). You may then want to determine the exception instead.

    That said, you normally shouldn't get a constraint violation on a primary key. In well designed datamodels which uses technical keys as primary keys they are normally to be managed by the database itself. Isn't the field supposed to be an unique key?

提交回复
热议问题