I am using spring data jpa
, spring boot
and h2
database.
My repository looks like this
public interface IComponentStorageRepository extends JpaRepository<ComponentData, String> {
}
My domain object looks like this
@Entity
@Table(name = "component_data")
public class ComponentData {
@Column(name = "component_id")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String componentId;
private String description;
with overriden equals
and hashcode
.
I have a service method that looks like this.
@Override
public void updateComponent(String componentId, String description) {
if (repository.existsById(componentId)) {
ComponentData stored = repository.getOne(componentId);
stored.setDescription(description);
repository.saveAndFlush(stored);
} else {
ComponentData stored = new ComponentData();
stored.setComponentId(componentId);
stored.setDescription(description;
repository.saveAndFlush(newResult);
}
}
It firstly performs a check if the object exists (to prevent EntityNotFound
exception) and then is trying to read one. If no object found it supposed to create a new one.
But each time I am trying to invoke the method - it is never able to find the entity. Every time it creates a new one.
I originally used repository.save
and had @Transactional
over the method but it didn't help either. I also haven't specified any properties and use everything default.
What is the problem
@GeneratedValue(strategy = GenerationType.IDENTITY ) can't be used with String type and what i know it's not supported by the H2 inmemory DB.
When you want to use the key as String you have to assign it manually before persisting without @GeneratedValue anotation or define the @GeneratedValue for String type properly.
There is an example from @VladMichalcea https://vladmihalcea.com/hibernate-and-uuid-identifiers/ .
Another option would be to change the type of the primary key to be @GeneratedValue supported types long (Long), int(Integer).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.