0
I managed a project by JHipster
who uses Java
, Spring
and Hibernate
in 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 point is that when I have a record saved (Rest class):
@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);
}
Which in turn calls the function save 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 bank:
public interface GrupoRepository extends JpaRepository<Grupo,Long> {
}
If I send save an object 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 have already dealt with, but when I save a new record the generated code for the id is skipped at +1, thus getting a lost id.
Ex:
- Save the group: To (id generated: 1)
- Save the group: To (error because there is already value in the bank)
- Save the group: AS (id generated: 3)
Note that I lost id 2.
Someone knows an elegant way to solve this problem, without having to create a new query before save to check if the name has already been registered?