简体   繁体   English

从未通过ID找到的Spring Data JPA实体

[英]spring data jpa entity never found by id

I am using spring data jpa , spring boot and h2 database. 我正在使用spring data jpaspring booth2数据库。

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 . 具有重写的equalshashcode

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. 它首先执行该对象是否存在的检查(以防止EntityNotFound异常),然后尝试读取该对象。 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. 我最初使用repository.save并在方法上使用了@Transactional ,但它也无济于事。 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. @GeneratedValue(strategy = GenerationType.IDENTITY )不能与String类型一起使用,我知道H2内存数据库不支持它。

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. 如果要将键用作字符串,则必须在不使用@GeneratedValue批注进行持久化之前手动分配它,或为String类型正确定义@GeneratedValue。

There is an example from @VladMichalcea https://vladmihalcea.com/hibernate-and-uuid-identifiers/ . @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). 另一个选择是将主键的类型更改为@GeneratedValue支持的类型long(Long),int(Integer)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM