【问题标题】:CustomRepository clashes with <S>save(S) in org.springframework.data.repository.CrudRepository return type java.lang.Long is not compatible with SCustomRepository 与 org.springframework.data.repository.CrudRepository 中的 <S>save(S) 冲突返回类型 java.lang.Long 与 S 不兼容
【发布时间】:2021-03-15 18:29:57
【问题描述】:

我正在尝试在数据库中保存一条记录,作为回报应该返回我主键。

这是我的实体类:

@Entity
public class CustomEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
private Integer eventTypeId;
//getter setter here
}

这是我的存储库:

public interface CustomRepository extends JpaRepository<CustomEntity, Long> {
Long save(customRepository);
}

当我尝试在我的服务类中调用存储库接口时,我在编译时收到此异常:

Error:(32, 8) java: save(model.CustomEntity) in repository.CustomRepository clashes with <S>save(S) 
in org.springframework.data.repository.CrudRepository return type java.lang.Long is not compatible with S

我了解 JPA Repository 扩展了 PaginationAndSorting,它在返回中扩展了 CrudRepository,我该如何解决这个问题。

【问题讨论】:

    标签: java spring hibernate jpa


    【解决方案1】:

    方法签名是

    <S extends T> S save(S entity)
    

    因此您需要返回与作为参数传递的相同类型。在你的情况下CustomEntity

    【讨论】:

    • 我明白了,但是我保存的时候不能直接得到主键作为返回吗?
    • 不,但更好的是,您可以使用主键集返回整个对象 :-)
    【解决方案2】:

    参数的类型和返回值应该相同。 尝试更改您的代码:

    public interface CustomRepository extends JpaRepository<CustomEntity, Long> {
    CustomEntity save(customRepository);
    }
    

    然后从CustomEntity对象中获取id值,例如:

    public void someMethod(){
      CustomEntity entity = repo.save(new CustomEntity());
      Long savedId = entity.getId();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多