title: Correct way to check for foreign key constraint violation in Hibernate?
body: <p>I have two tables that already exist inside postgres, lets call the Table A and Table B. One column of Table B has a foreign key constraint in that it has to be the primary key of Table A. Thus there is a many-to-one relationship between B and A, where multiple records in Table B correspond to one record of Table A.</p>
  <p>The Entity for both these tables are defined as follows.</p>
  <pre><code>public class TableA implements Serializable {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = &quot;user_id&quot;)
  private Long userId;
  
  @Column(name = &quot;name&quot;)
  private String name;
  
  @Column(name = &quot;email&quot;)
  private String email;
  
  @Column(name = &quot;phone_number&quot;)
  private String phoneNumber;
  }
  </code></pre>
  <p>TableB's entity is defined as follows:</p>
  <pre><code>public class Shots implements Serializable {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = &quot;item_id&quot;)
  private Long itemId;
  
  @Column(name = &quot;user_id&quot;)
  private Long userId;
  }
  </code></pre>
  <p>Where userId is the foreign key mapping to the primary key user_id in Table A.
  These constraints have already been defined in the underlying postgres database, so i didn't consider using the @ManyToOne annotation relationship (still trying to wrap my head around it).</p>
  <p>The way i currently handle the case when a foreign key constraint violation occurs is by doing the following:</p>
  <pre><code>try {
          tableBrepository.save(newShot);
      } catch (ConstraintViolationException ex) {
          logger.error(&quot;Violating foreign key constraint&quot; + ex.getMessage());
      }
  </code></pre>
  <p>My question is, is there a better way to check for this violation? Is there anything i can do to generally better structure the foreign key constraint in Spring Data JPA?</p>