У меня есть таблица Country and State, для которой я интегрирован с Spring Data JPA. Я создал функцию public Page<CountryDetails> getAllCountryDetails
в моей CountryServiceImpl для получения всей страны и соответствующих данных о состоянии. Услуга работает нормально и дает мне следующий результат:
{
"content": [
{
"id": 123,
"countryName": "USA",
"countryCode": "USA",
"countryDetails": "XXXXXXXX",
"countryZone": "XXXXXXX",
"states": [
{
"id": 23,
"stateName": "Washington DC",
"countryCode": "USA",
"stateCode": "WAS",
"stateDetails": "XXXXX",
"stateZone": "YYYYYY"
},
{
"id": 24,
"stateName": "Some Other States",
"countryCode": "USA",
"stateCode": "SOS",
"stateDetails": "XXXXX",
"stateZone": "YYYYYY"
}
]
}
],
"last": false,
"totalPages": 28,
"totalElements": 326,
"size": 12,
"number": 0,
"sort": null,
"numberOfElements": 12,
"first": true
}
Мой полный код приведен ниже:
CountryRepository.java
@Repository
public interface CountryRepository extends JpaRepository<CountryDetails, Integer> {
@Query(value = "SELECT country FROM Country country GROUP BY country.countryId ORDER BY ?#{#pageable}",
countQuery = "SELECT COUNT(*) FROM Country country GROUP BY country.countryId ORDER BY ?#{#pageable}")
public Page<CountryDetails> findAll(Pageable pageRequest);
}
CountryServiceImpl.java
@Service
public class CountryServiceImpl implements CountryService {
@Autowired
private CountryRepository countryRepository;
@Override
public Page<CountryDetails> getAllCountryDetails(final int page, final int size) {
return countryRepository.findAll(new PageRequest(page, size));
}
}
CountryDetails.java
@Entity
@Table(name = "country", uniqueConstraints = @UniqueConstraint(columnNames = "id"))
public class CountryDetails {
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
private Integer id;
private String countryName;
private String countryCode;
private String countryDetails;
private String countryZone;
@JsonManagedReference
@OneToMany(fetch = FetchType.LAZY, mappedBy = "countryDetails")
private List<State> states;
// getters / setters omitted
}
State.java
@Entity
@Table(name = "state", uniqueConstraints = @UniqueConstraint(columnNames = "id"))
public class State {
@Id
@GeneratedValue
@Column(name = "id", unique = true, nullable = false)
private Integer id;
private String stateName;
private String countryCode;
private String stateCode;
private String stateDetails;
private String stateZone;
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countryCode", nullable = false, insertable = false, updatable = false, foreignKey = @javax.persistence.ForeignKey(name="none",value = ConstraintMode.NO_CONSTRAINT))
private CountryDetails countryDetails;
// getters / setters omitted
}
Теперь проблема
Фактически, что я хочу, чтобы служба страны возвращалась с минимальной информацией, как показано ниже
{
"content": [
{
"countryName": "USA",
"countryCode": "USA",
"states": [
{
"stateCode": "WAS"
},
{
"stateCode": "SOS"
}
]
}
],
"last": false,
"totalPages": 28,
"totalElements": 326,
"size": 12,
"number": 0,
"sort": null,
"numberOfElements": 12,
"first": true
}
Поэтому для достижения того, что я использовал Прогнозы, как показано ниже
CountryProjection.java
public interface CountryProjection {
public String getCountryName();
public String getCountryCode();
public List<StateProjection> getStates();
}
StateProjection.java
public interface StateProjection {
public String getStateCode();
}
CountryServiceImpl.java
@Repository
public interface CountryRepository extends JpaRepository<CountryDetails, Integer> {
@Query(value = "SELECT country.countryName AS countryName, country.countryCode AS countryCode FROM Country country GROUP BY country.countryId ORDER BY ?#{#pageable}",
countQuery = "SELECT COUNT(*) FROM Country country GROUP BY country.countryId ORDER BY ?#{#pageable}")
public Page<CountryProjection> findAll(Pageable pageRequest);
}
Но теперь служба возвращает любые данные состояния, как показано ниже
{
"content": [
{
"countryName": "USA",
"countryCode": "USA"
}
],
"last": false,
"totalPages": 28,
"totalElements": 326,
"size": 12,
"number": 0,
"sort": null,
"numberOfElements": 12,
"first": true
}
Как мы можем получить минимальные сведения о состоянии, как показано ниже
{
"content": [
{
"countryName": "USA",
"countryCode": "USA",
"states": [
{
"stateCode": "WAS"
},
{
"stateCode": "SOS"
}
]
}
],
"last": false,
"totalPages": 28,
"totalElements": 326,
"size": 12,
"number": 0,
"sort": null,
"numberOfElements": 12,
"first": true
}
Может ли кто-нибудь помочь мне в этом