Spring / J2EE:获取一个实体及其子代

时间:2016-06-15 14:46:33

标签: hibernate spring-mvc spring-data

我想用一组嵌套实体加载一个实体。 我是这样做的:

实体父亲

@OneToMany(mappedBy = "father")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
 @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@chilId")
    private Set<Child> children = new HashSet<>();

实体儿童

@ManyToOne
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@fatherId")
    private Father father;

在Spring MVC Rest控制器中,我正在加载一个父亲。

@RequestMapping(value = "/fathers/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional(readOnly = true)
    public ResponseEntity<Father> getLot(@PathVariable Long id) {
        Father father = fatherRepository.findOne(id);
        return Optional.ofNullable(father)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

Father father = fatherRepository.findOne(id);如果我调试父亲,我正在接收它的孩子,没关系。

但是如果我在我的数据库中添加一个孩子(在另一个弹簧控制器中):

@RequestMapping(value = "/children",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional
    public ResponseEntity<Child> createStock(@RequestBody Child child) throws URISyntaxException {
        if (child.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("child", "idexists", "A new child cannot already have an ID")).body(null);
        }
        Child result = stockRepository.save(child);
        return ResponseEntity.created(new URI("/api/stocks/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("child", result.getId().toString()))
            .body(result);
    }

如果那时我加载了一个父实体,我没有得到我为这个父亲创建的新孩子 我认为与@transactionnal注释有关,但我看不出是什么。

[UPDATE] 我设法得到了我想要的东西。 如下所示:

Father father = ownerRepository.findOne(id);
Child child= new Car();
child.setFather(father);
child = carrepository.save(child);
father.getChildren().add(child);
father = ownerRepository.save(father);
father = ownerRepository.findOne(id);

如果我这样做:

Father father = ownerRepository.findOne(id);
Child child= new Car();
child.setFather(father);
child = carrepository.save(child);
father = ownerRepository.findOne(id);

我在保存孩子后取回父亲时,我没有在父对象中得到新孩子。

2 个答案:

答案 0 :(得分:0)

我认为这是因为交易没有提交或刷新

看看:@EnableTransactionManagement告诉Spring,带有@Transactional注释的类应该用Transactional Aspect包装。有了这个,现在可以使用@Transactional了。

答案 1 :(得分:0)

尝试将FetchType.EAGER与父实体一起使用。所以这将在你获取父实体时加载孩子。希望这能帮到你!