0

I hava deleteNotice method using jpaRepository.

public Notice deleteNotice(int id) {
    Notice notice = noticeRepository.findByIdAndVisible(id, true)
            .orElseThrow(() -> new EntityNotFoundException(String.valueOf(id)));
    
    notice.setVisible(false);
            
    return noticeRepository.save(notice);   
}

And there is an entity file.

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Notice {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Size(min=4, max=10, message="Title should have at least 4 characters")
    private String title;
    
    @JsonIgnore
    private boolean visible;
}

When I try this deleteNotice in controller,

@DeleteMapping("/notice/{noticeId}")
public ResponseEntity<Object> deleteNotice(@PathVariable int noticeId){
    return ResponseEntity.ok(noticeService.deleteNotice(noticeId));
}

I got an error "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction".
Could I get some advice for this problem?

DD DD
  • 1,148
  • 1
  • 10
  • 33
  • 1
    `nested exception`: That's saying _there is a cause_, which you didn't include. Always post the entire stack trace. (Note also that with JPA repositories _specifically_, it's not required to call `save` after making changes, because the JPA instrumentation does that magically. It is necessary with other repositories.) – chrylis -cautiouslyoptimistic- May 02 '21 at 01:51
  • I do not know what causing issue. But you can try to add @Transactional annotation on deleteNotice ins service method. Better you can add whole stack traces. – sandip May 02 '21 at 02:14

1 Answers1

-1

Put @transactional over your service class.

This error might come when your entity retrieved by the entity manager is in persistent state and after making your changes when you want to commit, that entity is still in use by another program. For additional info

Similar problem is asked on stackoverflow

Manish Bansal
  • 819
  • 2
  • 8
  • 19