I generated a project by JHipster
which uses Java
, Spring
and Hibernate
in the backend, I created a class as follows:
Liquibase:
<changeSet id="20160504131602" author="jhipster">
<createTable tableName="grupo">
<column name="id" type="bigint" autoIncrement="${autoIncrement}">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="nm_grupo" type="varchar(35)">
<constraints unique="true" nullable="false" />
</column>
</createTable>
Domain:
@Entity
@Table(name = "grupo")
@Document(indexName = "grupo")
public class Grupo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(min = 1, max = 35)
@Column(name = "nm_grupo", length = 35, unique = true, nullable = false)
private String nmGrupo;
The issue is that when I command to save a record (Class rest):
@RequestMapping(value = "/grupos",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Grupo> createGrupo(@Valid @RequestBody Grupo grupo) throws URISyntaxException {
log.debug("REST request to save Grupo : {}", grupo);
if (grupo.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("grupo", "idexists", "A new grupo cannot already have an ID")).body(null);
}
Grupo result = grupoService.save(grupo);
return ResponseEntity.created(new URI("/api/grupos/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("grupo", result.getId().toString()))
.body(result);
}
That in turn calls the save function of the implementation class:
public Grupo save(Grupo grupo) {
log.debug("Request to save Grupo : {}", grupo);
Grupo result = grupoRepository.save(grupo);
grupoSearchRepository.save(result);
return result;
}
Saving the object physically in the database:
public interface GrupoRepository extends JpaRepository<Grupo,Long> {
}
If I have an object saved with a name already registered in the database, hibernate returns the error:
ERROR: duplicate key value violates unique constraint "group_nm_group_key" **
This error I already dealt, however when I save a new record the generated code for the id is jumped on +1, thus getting a lost id.
Ex:
Notice that I lost id 2.
Does anyone know an elegant way to solve this problem, without having to create a new query before the save to verify that the name has already been registered?