janssen-dev
janssen-dev

Reputation: 2771

Hibernate does not throw an exception on duplicate primary key

I am working with Spring Data JPA. Given this setup:

@Entity
public class Role
{
    @Id
    @Column(nullable = false, unique = true)
    private String name;

    @Column
    private String info;
}

@Repository
public interface RoleRepository extends CrudRepository<Role, String>
{
}

I can simply insert a Role with the same primary key (name) twice. It justs updates the entry in the database. I would like it to throw an exception though. Trying to insert two entries with the same primary key at database-level gives the desired "duplicate key"-error.


Example:

Role table is empty

MariaDB [logz]> select * from role;
Empty set (0.00 sec)

Saving the first time

roleRepository.save(new Role("name1", "info0"));

Hibernate first checking, then saving

Hibernate: select role0_.name as name1_3_0_, role0_.info as info2_3_0_ from role role0_ where role0_.name=?
Hibernate: insert into role (info, name) values (?, ?)

Role table is filled

MariaDB [logz]> select * from role;
+-------+-------+
| name  | info  |
+-------+-------+
| name1 | info0 |
+-------+-------+
1 row in set (0.00 sec)

Saving the second time

roleRepository.save(new Role("name1", "info1"));

Hibernate checking and updating - I want an exception here though!

Hibernate: select role0_.name as name1_3_0_, role0_.info as info2_3_0_ from role role0_ where role0_.name=?
Hibernate: update role set info=? where name=?

Role table is simply updated :(

MariaDB [logz]> select * from role;
+-------+-------+
| name  | info  |
+-------+-------+
| name1 | info1 |
+-------+-------+
1 row in set (0.00 sec)

Upvotes: 1

Views: 2845

Answers (1)

NiVeR
NiVeR

Reputation: 9806

If you look at the implementation of the save method it is like this:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

so you can notice that it will do update in case an object with a particular id is already present in the database. If you are further interested you can find the source here.

Upvotes: 2

Related Questions