0

我正在尝试使用 gradle 在 quarkus 上测试 1:m 映射。使用的扩展:

quarkus-hibernate-orm-panache'

夸库斯弹簧网'

邮差:

在 http://localhost:8080/tree 上发布请求:

{
"name":"mango",
"fruits": [
    {"name":"a",
     "color":"red"
    },
    {"name":"b",
     "color":"yellow"
    }
]
}

现在当在 http://localhost:8080/tree 上做 GET 时,水果是空的。为什么它是空的无法找到。

[
    {
        "treeId": 1,
        "name": "mango",
        "fruits": []
    }
]

我使用了以下 1 个控制器类和 2 个实体类。

@RestController
public class TreeController {
    
    @PostMapping("/tree")
    @Transactional
    public void addTree(Tree tree) {
        Tree.persist(tree);
    }
    
    @GetMapping("/tree")
    public List<Tree> getTree() {
        return Tree.listAll();
        
    }
}

@Entity
public class Tree extends PanacheEntityBase{
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long treeId;
    
    public String name;
    
    @OneToMany(mappedBy = "tree", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    public List<Fruit> fruits;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Fruit> getFruits() {
        return fruits;
    }

    public void setFruits(List<Fruit> fruits) {
        this.fruits = fruits;
    }

    public Long getTreeId() {
        return treeId;
    }

    public void setTreeId(Long treeId) {
        this.treeId = treeId;
    }



}

@Entity
public class Fruit extends PanacheEntityBase {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long fruitId;
    public String name;
    public String color;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="treeId")
    public Tree tree;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }

    public Long getFruitId() {
        return fruitId;
    }

    public void setFruitId(Long fruitId) {
        this.fruitId = fruitId;
    }
}
4

1 回答 1

2

您可以在坚持之前尝试设置反向引用吗?

@RestController
public class TreeController {
    
    @PostMapping("/tree")
    @Transactional
    public void addTree(Tree tree) {
        for(Fruit fruit : tree.fruits)
             fruit.tree = tree;
        Tree.persist(tree);
    }
    
    @GetMapping("/tree")
    public List<Tree> getTree() {
        return Tree.listAll();
        
    }
}
于 2021-03-26T13:34:22.560 回答