【问题标题】:Spring boot JPA - Custom Repository for multiple EntitySpring boot JPA - 多个实体的自定义存储库
【发布时间】:2019-07-28 08:46:37
【问题描述】:

我的 JPA 休息项目遇到了一些困难。 我已经为我的每个实体(我的数据库中的表)构建了我的存储库,并且工作正常。 例如,我的实体“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);
}

我的问题:返回结果始终是“Personne”类型。

我想发出一个本机请求,将带有自定义属性的对象发回给我。

期望回报的例子:

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

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

【问题讨论】:

    标签: rest spring-boot jpa repository


    【解决方案1】:

    你可以使用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
      }
    }
    

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

    【讨论】:

    • 感谢您的回复。我知道预测,但是对于我需要的东西,我认为使用它们太复杂了。确实,我必须对很多表(8 个表)提出请求,而预测似乎并不是最好的。
    • 它工作正常!非常感谢 !我只是忘记在我的@Query 中设置 nativeQuery = true ...
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2018-10-06
    • 2017-11-24
    • 2021-11-07
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多