I am working on an existing database and I am not allowed to modify any table.
I have the following entity: PostCharge Entity
@Entity
@Data // from lombok
@AllArgsConstructor // from lombok
@NoArgsConstructor // from lombok
public class postCharge {
@Id
private Integer id;
private String cat;
private Integer catId;
private String code;
}
Now, I have 3 different tables named: Cat1, Cat2, and Cat3. The field cat will hold the value like c1 or c2 or c3 to identity the table and catId will hold the ID of the object from the selected cat table.
I have the following EntityDTO (using MapStruct): PostChargeDTO
@Entity
@Data // from lombok
public class postChargeDTO {
private Integer id;
private String cat;
private Integer catId;
}
DTO Mapper
@Mapper(componentModel = "spring")
public interface PostChargeMapper {
List<PostChargeDTO> postChargeToDTOList(List<PostCharge> postCharges);
}
PostChargeRespositoty
@Repository
public interface PostChargeRepository extends JpaRepository<PostCharge, Integer> {
List<PostCharge> findAllByCat(String cat);
}
Service
@Service
public class PostChargeService {
@Autowired
private PostChargeRepository postChargeRepository;
public List<PostCharge> fetchPostChargeList(String cat) {
return postChargeRepository.findAllByCat(cat);
}
}
Controller
@RestController
@RequestMapping("/api/post-charge")
public class PostChargeController {
@Autowired
private PostChargeService postChargeService;
@Autowired
private PostChargeMapper postChargeMapper;
@GetMapping("/list")
public List<PostChargeDTO> fetchPostChargeList(
@RequestParam(name = "cat") String cat) {
return postChargeMapper.postChargeToDTOList(postChargeService.fetchPostChargeList(cat));
}
}
List Response
{
{
"id": 1,
"cat": "c1",
"catId": 2
},
{
"id": 2,
"cat": "c2",
"catId": 2
},
{
"id": 1,
"cat": "c1",
"catId": 3
},
{
"id": 1,
"cat": "c3",
"catId": 5
},
}
Now how do I replace the catId value with the value from any other column from the respective cat table?
Like if table c3 with catId 5 has a column named as the title with the value "foo". How do I get this "foo" to display in that JSON in the respective object?
So instead of "catId": 5, I want to get "catId": "foo" or maybe a new key with the value if needed to achieve the result.
I am new to spring-boot and Thank you for any help.