【问题标题】:How to get an entity's property composed by other properties from database?如何从数据库中获取由其他属性组成的实体属性?
【发布时间】:2017-02-16 11:36:21
【问题描述】:

我有这个实体:

public class T_compteBancaire implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long                   id_compteBancaire;

@Transient
private String                 ibanCodePays;

@Transient
private String                 ibanCleIban;

@Transient
private String                 ibanCodeBanque;

@Transient
private String                 ibanCodeGuichet;

@Transient
private String                 ibanNumeroCompte1;

@Transient
private String                 ibanNumeroCompte2;

@Transient
private String                 ibanNumeroCompte3;

@Transient
private String                 ibanCleRib;

//Only this property is stored in DB
@Column( name = "IBAN" )
private String                 ibanComplet;

public String getIbanComplet() {
    ibanComplet = ibanCodePays + ibanCleIban + " " + ibanCodeBanque + " " + ibanCodeGuichet
            + " " + ibanNumeroCompte1 + " " + ibanNumeroCompte2 + " " + ibanNumeroCompte3 + " " + ibanCleRib;
    return ibanComplet;
}

@OneToOne
private User             owner;

//Other getters and setters
}

问题是当我从数据库中检索我的实体并调用getIbanComplet() 方法时,结果是nullnull null null null null null null。 我不想将其他属性存储到数据库。我该如何解决这个问题?

我在 Spring MVC 应用程序中使用 SpringDataJPA + Hibernate。

非常感谢。

【问题讨论】:

    标签: mysql hibernate spring-mvc null spring-data-jpa


    【解决方案1】:

    您必须先将 IBAN 号码拆分为每个属性。有多种方法可以做到这一点,例如,在 setter 方法中,创建一个新方法以在加载实体后提取这些属性,或者使用 JPQL 查询使用 select new package.Class() 来拆分它们,例如带有子字符串。

    【讨论】:

    • 感谢您的回复。没有其他神奇的解决方案吗?例如。一个 sql 请求,它只会将 IBAN 作为字符串返回,然后使用 Substring + Setters 进行拆分。
    【解决方案2】:

    我通过使用本机查询解决了这个问题。 这是我的解决方案:

    public interface TcompteBancaireRepository extends JpaRepository<T_compteBancaire, Long> {
    
    @Query( value = "select cb.iban from T_compteBancaire cb where cb.owner_id =?1", nativeQuery = true )
    String findIBANbyOwnerID( Long ownerID );
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多