Having the following database structure:
I have defined the Models as follow:
Ticket Class:
@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...
}
Category Class:
@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<>();
}
I have two more classes for Subcategory and Template which are linked with a @ManyToMany relationship as well as Category. For these ones it is fine.
I have the following clean Repository and Controller for the Tickets:
public interface TicketRepository extends JpaRepository<Ticket, Long>{
}
This is just for testing JPA so it's a simple findAll controller:
@RestController
@CrossOrigin(origins = "*")
@RequestMapping(value = "/api")
public class TicketController {
@Autowired
private TicketRepository ticketRepository;
@GetMapping("/tickets")
public List<Ticket> getTickets() {
return ticketRepository.findAll();
}
}
While doing a request to this endpoint the Json will be something like:
[{
"ticketId": 1,
"categoryId": {
"categoryId": 1,
"description": "dsadsadsa",
"subcategories": [{
"subCategoryId": 1,
"description": "dsadasdsad",
"templates": [{
"description": "adsadsadsa",
"id": 1
}]
}]
},
"description": "dasdasdas"
}]
Can you please let me know how I can have only the category_id in the object? - So the JSON would look like:
[{
"ticketId": 1,
"categoryId": 1,
"description": "dasdasdas"
}]
Thanks