0

I've a JPA Entity which has a unique constraint based on multiple columns, I'm trying to handle and generate a human friendly error message but somehow spring/hibernate is stealing the exception from me

@Entity
@Table(name = "columns", uniqueConstraints = {@UniqueConstraint(columnNames = {"position", "board_id"}, name = UNIQUE_COLUMN_BOARD_POSITION)})
public class Column {
//some stuff
}

Then i have the service class

   @Transactional
       @NonNull
       public Column update(long columnId, @NonNull Column transientColumn) {


      Column persistentColumn = get(columnId);
      persistentColumn.setTitle(transientColumn.getTitle());
      persistentColumn.setPosition(transientColumn.getPosition());

      try {
         return columnRepository.save(persistentColumn);
      } catch (Exception e) {
         System.out.println(e); //NEVER REACHES HERE
      }

      return transientColumn;
   }

I'm writing my test clases so I autowired the service class, I intentionaly try to update a column to break the unique contraint, hibernate stops the update throw a giant exception... BUT WONT LET ME CAPTURE THE EXCEPTION

I've debugged line by line, the code reaches the save line, then spring/hibernate code starts to run, after that the exception is thrown but my catch clause never gets it and the test finishes

here is the test class

 @Test
   void testFailUpdateDueRepeatedPosition() {

      Column column = new Column(persistentBoard, "column", 1);
      Column column2 = new Column(persistentBoard, "column", 2);

      column = columnRepository.save(column);
      column2 = columnRepository.save(column2);


      column2.setPosition(1);
      columnService.update(column2.getId(), column2);


      columnRepository.delete(column);
   }

I don't care if I can't catch this exception all i want is to have a custom message which i can set in case it happens

Rafael Lima
  • 3,079
  • 3
  • 41
  • 105
  • 1
    I don't exactly remember the internals of JPA+Hibernate+Spring, but I believe your actual save (db insert/update) is being run when the `@Transactional`marked/wrapped `update` method finishes – Ale Zalazar Jun 30 '22 at 22:01
  • Does this answer your question? [Add a Custom message for the Unique Constraints in hibernate](https://stackoverflow.com/questions/50466545/add-a-custom-message-for-the-unique-constraints-in-hibernate) – Ale Zalazar Jun 30 '22 at 22:05
  • @AleZalazar, no because the other person is using a single column constraint... and I'm using multiple column, so I cant annotate the field like he did – Rafael Lima Jun 30 '22 at 23:07

0 Answers0