@ManyToOne关系:没有完整的ForeignKey对象的GetRequest

时间:2019-01-03 12:22:05

标签: spring hibernate spring-boot jpa spring-data-jpa

具有以下数据库结构:

enter image description here

我对模型的定义如下:

门票课程:

@Entity
@Table(name = "TICKET")
public class Ticket {

    @Id
    @Column(name = "id")
    private Long ticketId;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "categoryId")
    private Category categoryId;

    private String description;

    // Ommiting Getters and Setters for abreviation...

}

类别类别:

@Entity
@Table(name = "CATEGORIES")
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long categoryId;

    private String description;

    @JsonManagedReference
    @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
    @JoinTable(name = "CATEGORY_SUBCATEGORIES", joinColumns = @JoinColumn(name = "category_id"), inverseJoinColumns = @JoinColumn(name = "subcategory_id"))
    private Set<Subcategory> subcategories = new HashSet<>();
}

我还有两个用于Subcategory和Template的类,它们与@ManyToMany关系以及Category关联。对于这些,这很好。

我有以下用于票据的干净的存储库和控制器:

public interface TicketRepository extends JpaRepository<Ticket, Long>{

}

这只是用于测试JPA,因此它是一个简单的findAll控制器:

@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/api")
public class TicketController {

    @Autowired
    private TicketRepository ticketRepository;

    @GetMapping("/tickets")
    public List<Ticket> getTickets() {
        return ticketRepository.findAll();
    }
}

在向此终结点发出请求时,Json将类似于:

[{
  "ticketId": 1,
  "categoryId": {
    "categoryId": 1,
    "description": "dsadsadsa",
    "subcategories": [{
      "subCategoryId": 1,
      "description": "dsadasdsad",
      "templates": [{
        "description": "adsadsadsa",
        "id": 1
      }]
    }]
  },
  "description": "dasdasdas"
}]

可以让我知道如何仅在对象中包含category_id吗? -因此JSON如下所示:

[{
  "ticketId": 1,
  "categoryId": 1,
  "description": "dasdasdas"
}]

谢谢

0 个答案:

没有答案