Unique Constraint error thrown at the end of @Transactional block [Java/JPA]

Suppose I have a user class:

public class User {

    @GeneratedValue(strategy = GenerationType.AUTO)
    Long userKey;

    @Column(unique = true)
    String someId;

    String name;

And it’s corresponding service

public class UserService {

    UserRepository repository;

    public User createUserWithId(String name, String id) {
        User userToAdd = User.builder()
        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.

Know someone who can answer?

Hi, I’ve changed the category & added the language and framework you’re asking for help with. I am not familiar with Java but think JPA is correct? If not, apologies & you’ll need to amend the title of your post.

You originally posted under the category for JavaScript, you’ll be more likely to get help if you specify the language and post in the general category.