【发布时间】:2020-06-21 15:01:23
【问题描述】:
在我的 spring-boot 项目中,我想创建具有父值和子值的对象“菜单”:
- 菜单可以有一个父元素
- 菜单可以有一个或多个子元素
实体 Menu.java
@Entity
@Data @AllArgsConstructor @NoArgsConstructor
public class Menu implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
private List<Menu> childrens;
@ManyToOne
private Menu parent;
}
MenuDAO.java
@RepositoryRestResource
public interface MenuDAO extends JpaRepository<Menu, Long> {
}
DemoApplication.java 添加数据以使用 CommandLine Runner 进行测试:
-
Menu1(父级)
- Sub-Menu1(Menu1 的子级)
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
MenuDAO menuDAO;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Menu m1 = menuDAO.save(new Menu(null,"Menu1",null,null));
Menu m2 = menuDAO.save(new Menu(null,"Sub-Menu1",null,m1));
}
}
但是当我通过休息服务调用获取父元素时,我得到了这个结果http://localhost:9090/menus/1:
{
"name" : "Menu1",
"_links" : {
"self" : {
"href" : "http://localhost:9090/menus/1"
},
"menu" : {
"href" : "http://localhost:9090/menus/1"
},
"childrens" : {
"href" : "http://localhost:9090/menus/1/childrens"
},
"parent" : {
"href" : "http://localhost:9090/menus/1/parent"
}
}
}
但我的要求是获取以下 JSON 格式的数据:
{
"name" : "Menu1",
"childrens" : [{
"name" : "Menu2"
}],
"parent" : NULL,
"_links" : {
"self" : {
"href" : "http://localhost:9090/menus/1"
},
"menu" : {
"href" : "http://localhost:9090/menus/1"
},
"childrens" : {
"href" : "http://localhost:9090/menus/1/childrens"
},
"parent" : {
"href" : "http://localhost:9090/menus/1/parent"
}
}
}
有什么建议吗?
【问题讨论】:
-
StackOverflow 应该是英文的
标签: hibernate spring-boot rest jpa entity-relationship