Suppose I have a user class:
@Entity
@Data
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long userKey;
@Column(unique = true)
String someId;
String name;
}
And it’s corresponding service
@Component
@Slf4j
public class UserService {
@Autowired
UserRepository repository;
@Transactional
public User createUserWithId(String name, String id) {
User userToAdd = User.builder()
.name(name)
.someId(id)
.build();
repository.save(userToAdd);
log.info("No issue in saving");
//some more code
return userToAdd;
}
}
As you can see that I have a unique constraint on someId field in User class but when I execute the method createUserWithId with same Id, I’d expect to get an error on the line containing repository.save() and the code after it to not be executed. But the code after it is getting executed and I’m getting an exception at the end of the transactional block. My question is why this is happening and what are the exceptions which I would generally get when interacting with the repository object ( like in this case repository.save ) and which type of exceptions will I get at the end of transactional block ?
PS I am calling the UserService from inside a simple controller and I have created an empty UserRepository which just extends CrudRepository. Both of which I have left out from the question for brevity but let me know if adding them here would make sense.