Spring 启动 JPA - 多个实体的自定义存储库

Spring boot JPA - Custom Repository for multiple Entity

我的 JPA Rest 项目遇到了一些困难。 我已经为我的每个实体(我的数据库中的表)构建了我的存储库,并且它工作正常。 例如,我实体的一部分 "Personne" :

@Entity
public class Personne {
private Long id;
private String nom;
private String prenom;
private Date dateNaissance;
private String telDomicile;
private String telPortable;
private String telAutre;
private String telCommentaire;
private String fax;
private String mail;
private String commentaire;
private Timestamp dateSuppr;
private String sexe;
private Patient patientById;
private Adresse adresseByAdresseId;

@Id
@JsonProperty(value = "dataId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

}

以及带有 @Query 的 myRepository :

@Transactional
@RepositoryRestResource(collectionResourceRel = "personne", path = "personne", excerptProjection = InlinePersonne.class)
public interface PersonneRepo extends JpaRepository<Personne, Long> {
@Query("from Personne p where p.nom = ?1 and p.prenom = ?2")
public Personne customRequest(String nom, String prenom);
}

我的问题:return 结果总是类型 "Personne"。

我想发出一个本机请求,向我发送一个具有自定义属性的对象。

希望的例子 return :

{object :
    {name : String,
    surname : String,
    age : int },
    adresse :{
        city : String,
        street : String
    }
}

可以吗? 我真的需要它,因为我必须在许多表上提出复杂的请求。 谢谢。

您可以使用 interface-base projections:

首先创建反映所需字段的界面:

interface PersonSummary {

  String getName();
  String getSurename();
  int getAge();

  AddressSummary getAddress();

  interface AddressSummary {
    String getCity();
    String getStreet();
  }
}

然后指示您的自定义查询需要扩展和实例化什么接口来填充信息:

public interface PersonneRepo extends JpaRepository<Personne, Long> {
    // All your other abstract method

    // Brand new query
    @Query("Select p.name, p.surname, p.age, p.city, p.street from Personne p where p.nom = ?1 and p.prenom = ?2")
    public PersonSummary customRequest(String nom, String prenom);
}

您将收到这样的对象:

{
  name : String,
  surname : String,
  age : int,
  address :{
    city : String,
    street : String
  }
}

您需要根据要接收的对象的组合复杂性来测试此功能的灵活性。