0

I have a simple Department Entity with one attribute name which I set to be unique.

@Entity
@XmlRootElement
public class Department {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "id")
    private int id;

    @Basic
    @Column(name = "name", unique = true)
    private String name;

    @ManyToMany(mappedBy = "departments")
    @JsonbTransient
    @XmlTransient
    private Set<Employee> employees = new HashSet<Employee>();

...

    methods

}

And the following code to insert a new Department entry in my DB.

...

transaction.begin();

entityManager.createNativeQuery("insert into mydb.department (department.name)" +
                        "values (:deptName)", Department.class)
                        .setParameter("deptName", department.getName())
                        .executeUpdate();
                

transaction.commit();

...

Now after I run a few tests on Postman, I realized that even after trying to insert a duplicate Department and get the "message":"org.hibernate.exception.ConstraintViolationException: could not execute statement" exception, the ID of the next entry will be increased.

postman console output

I don't understand, what (MySQL, jdbc, javax.persistence, Hibernate) causes this?

Is this a normal behavior, or is there a way to fix this?

0 Answers0