繁体   English   中英

在Spring Data仓库上定制更新实体

[英]Customize update entity on Spring Data repository

我有XRepository接口(扩展了JpaRepository )。 在创建或更新X实体时,我需要在事务中调用另一个存储库( YRepository )的方法(确切地说:更新某些字段并在创建/更新的实体X使用新值)。

为此,我使用@Transactional方法和自定义REST Controller创建了服务类。 控制器上的POST映射可以正常工作,并且对我来说是可以接受的,但是在如何以更优雅的方式更新(PUT / PATCH)服务层中的现有实体时遇到问题。 它也可以使用,但是必须使用BeanUtils.copyProperties() 是更好,更常规的方法吗?

public interface XRepository extends JpaRepository<X, Long> {
}

public interface YRepository extends JpaRepository<Y, Long> {
}

@BasePathAwareController
public class XRestControllerCustom {

    @Autowired
    private MyService myService;

    @PostMapping("/x")
    public @ResponseBody ResponseEntity<X> create(@RequestBody Resource<X> x) {     
        return new ResponseEntity<X>(myService.save(x.getContent()), HttpStatus.CREATED);
    }

    @PatchMapping("/x/{id}")
    public @ResponseBody ResponseEntity<X> update(@PathVariable Long id, @RequestBody Resource<X> x) {
        myService.update(id, x.getContent());
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

@Component
public class MyService {

    @Autowired
    private XRepository xRepository;

    @Autowired
    private YRepository yRepository;

    @Transactional
    public X save(X x) {
        yRepository.update();
        x.setField(yRepository.get());
        return xRepository.save(x);
    }   

    @Transactional
    public X update(Long id, X partial) {
        X x = xRepository.getOne(id);
        BeanUtils.copyProperties(x, partial);
        x.setId(id); // because copyProperties makes id null
        yRepository.update();
        x.setField(yRepository.get());
        return xRepository.save(x);     
    }   
}

暂无
暂无

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

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