0

Having the following database structure:

enter image description here

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

thathashd
  • 1,022
  • 4
  • 17
  • 49
  • 1
    I prefere that you create a simple dto where you map your Tikcets in via mupstruct for example , bet if you do not like that approach you can check her https://stackoverflow.com/a/39960438/4373948 – Abder KRIMA Jan 03 '19 at 13:36
  • use mapstruct as @TinyOS suggested. and rename categoryId to category in Ticket class – prem kumar Jan 05 '19 at 10:19

0 Answers0