【问题标题】:How do I fetch a value in a ManyToOne relationship mapping via @Query?如何通过@Query 在多对一关系映射中获取值?
【发布时间】:2021-03-01 12:00:52
【问题描述】:

我正在尝试从表 SubContactModel 中获取多个列的不同值,在该表中我将使用 a 值进行搜索,在本例中为电子邮件。

虽然我能够获得不同的值,但我现在想要获得的是获取 a 中的值 使用@ManyToOne 映射的字段。截至目前,我只能获得外键(FK),但我想从关系中获取另一个值。例如,我想从 CountryPhoneCodeModel 中获取值 countryphonecode。我已经包含了我的存储库层,以展示我现在如何获得不同的值。

子联系人模型:

@Data
@Entity
public class SubContactModel implements Serializable {


    @Id
    @Column(name = "SUBCONTACTID", updatable = false, unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long subcontactID;
    
    @ManyToOne() 
    @JoinColumn(name="PRSNTITLEID", nullable=true, updatable=true)
    private PersonTitleModel personTitleID;  // Person Title
    
    @ManyToOne()
    @JoinColumn(name = "countryPhonecode", nullable = true, updatable = true)
    private CountryPhoneCodeModel countryPhoneCodeModel; // Country Code 

    
    @Column(name = "name", nullable = true, length = 50)
    private String name;

    
    @Column(name = "designation", nullable = true, length = 50)
    private String designation;

    @Column(name = "telnumber", nullable = true, length = 50)
    private String telnumber;

    @Column(name = "email", nullable = true, length = 50)
    private String email;
    
    @ManyToOne()
    @JoinColumn(name="PERSONID", nullable=true, updatable=true)
    private PersonModel personID;
    
}

国家电话代码型号:

public class CountryPhoneCodeModel implements Serializable {

    @Id
    @Column(name="CPHONECODEID",updatable = false,unique = true,nullable = false )
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long countryPhoneCodeID;
    
    @Column(name="CPHONECODE",updatable=true,nullable=false,length=50)
    private String countryPhoneCode;
    
    @Column(name="COUNTRYNAME",updatable=true,nullable=false,length=50)
    private String countryName;
    
    @Column(name="DIALCODE",updatable=true,nullable=false,length=50)
    private String dialCode;
}

存储层:

@Repository
public interface SubContactRepo extends JpaRepository<SubContactModel, Long> {
     
@Query(value="SELECT DISTINCT u.designation,u.name,u.telnumber,u.countryphonecode,u.prsntitleid FROM subcontactmodel u WHERE u.email = :email", nativeQuery = true)
    List <Object> findDistinctResult (String email);
}

【问题讨论】:

    标签: hibernate jpa spring-data-jpa spring-data


    【解决方案1】:

    我已经找到了解决办法:

    我删除了 nativeQuery = true 并更改了 @Query 中的字段名称以匹配我的实体中的名称,而不是数据库中的表列名称。

    @Query(value="SELECT DISTINCT u.designation,u.name,u.telnumber, u.countryPhoneCodeModel.countryPhoneCode ,u.personTitleID.personTitleName FROM SubContactModel u WHERE u.email= :email")
    List <Object> findDistinctResult (String email);
    
    

    现在它按我想要的方式工作了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 2014-06-14
      • 2013-08-25
      相关资源
      最近更新 更多