我正试图在DB中保存一条记录,作为回报,DB应该会返回主键。
这是我的实体类:
@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);
}
当我尝试调用Service类中的存储库接口时,我在编译时会得到以下异常:
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,我该如何解决这个问题。
方法签名是
<S extends T> S save(S entity)
因此您需要在作为参数传递时返回相同的Type。在您的案例中为CustomEntity
。
参数的类型和返回值应该相同。尝试更改您的代码:
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();
}