重写RestController方法后,我得到:org.springframework.dao.InvalidDataAccessApiUsageException:给定的id不能为null

问题描述

我想在我的投资组合项目中添加春季阴影,并使其完全宁静。这意味着我需要重写AbstractResource类(这是我的@RestController的基类)给出的方法,以根据需要对其进行编辑,当我这样做时,我会收到org.springframework.dao.InvalidDataAccessApiUsageException:给定的id不能为null !

我的项目如下:

  • 服务包
public interface AbstractService<ENTITY extends AbstractEntity> {

    ENTITY update(ENTITY entity);

    EntityModel<ENTITY> getById(Long id);

    ENTITY save(ENTITY entity);

    void delete(Long id);

    Collection<ENTITY> getAll();
}

public abstract class AbstractServiceImpl<ENTITY extends AbstractEntity> implements AbstractService<ENTITY> {

    protected abstract JpaRepository<ENTITY,Long> getRepository();

    @Override
    public Collection<ENTITY> getAll() {
        return getRepository().findAll();
    }

    @Override
    public EntityModel<ENTITY> getById(Long id) {
        return EntityModel.of(getRepository().getOne(id));
    }
}

@Service
public class UserServiceImpl extends AbstractServiceImpl<User> implements UserService {

    private final UserRepository userRepository;

    @Override
    protected JpaRepository<User,Long> getRepository() {
        return userRepository;
    }
}
  • 资源包
public abstract class AbstractResource<ENTITY extends AbstractEntity>{

    public abstract AbstractService<ENTITY> getService();

    @GetMapping(value = "/{id}",produces = {"application/hal+json"})
    public EntityModel<ENTITY> getById(@PathVariable("id") Long id) {
        return getService().getById(id);
    }

    @GetMapping
    public Collection<ENTITY> getAll() {
        return getService().getAll();
    }
}

当我这样离开时-一切正常-我得到预期的答复

@RestController
@RequestMapping("/api/users")
public class UserResource extends AbstractResource<User> {

    @Autowired
    private final UserService userService;

    @Override
    public AbstractService<User> getService() {
        return userService;
    }
}

当我尝试覆盖此方法时发生错误

@RestController
@RequestMapping("/api/users")
public class UserResource extends AbstractResource<User> {

    @Autowired
    private final UserService userService;

    @Override
    public AbstractService<User> getService() {
        return userService;
    }

    @Override
    public EntityModel<User> getById(Long id) {
        return userService.getById(id);
        or
        return super.getById(id);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)