JavaSpring中的SQL查询返回Null

时间:2019-06-18 17:29:36

标签: java rest spring-boot jpa jpql

我正在尝试通过Java Spring进行简单的SQL调用。数据库中有数据,但正在调用时返回空值列表。

有趣的是,当我选择特定的行时,它将返回正确的值。 (见下文)

BasicAccountAuditRepo.java

@Repository
public interface BasicAccountAuditRepository extends CrudRepository<BasicAccountAudit, BasicAccountAuditPK> {

    List<BasicAccountAudit> findAll();

//THIS RETURNS NULL
    @Query("SELECT b FROM BasicAccountAudit as b WHERE id.accountRef  = :accountRef ")  
    List<BasicAccountAudit> findByAccountRef(@Param("accountRef") String accountRef);

//This returns the correct values for dcConnName
    @Query("SELECT id.dcConnName FROM BasicAccountAudit WHERE id.accountRef  = :accountRef ")  
    List<BasicAccountAudit> findByAccountRef(@Param("accountRef") String accountRef);

}

我正在为模型类使用嵌入式ID。 BasicAccountAudit.java


@XmlRootElement
@Entity
@Table(name = "tb_Account_History", schema="dbo")

public class BasicAccountAudit implements Serializable{

    @EmbeddedId
    private BasicAccountAuditPK id;


    @Temporal(TemporalType.TIMESTAMP)
    @Column(insertable = true, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Date enteredDate;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(insertable = true, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Date lastUpdatedDate;


}

这是主键类: BasicAccountAuditPK.java

package org.fusion.restful.basicaccount.model;

import java.io.Serializable;

public class BasicAccountAuditPK implements Serializable {

    private String accountRef;
    private String client;
    private String dcEligible;
    private String shortCode;
    private String loadCps;
    private String stpFlag;
    private String accountType;
    private String clearingFirm;
    private String exchange;
    private String dcConnName;
    private String status; 
    private String enteredBy;

 //getters and setters...
}

1 个答案:

答案 0 :(得分:0)

您需要与别名用法保持一致。 在第一个查询中,您忘记了where子句中的别名:

"SELECT b FROM BasicAccountAudit as b WHERE id.accountRef  = :accountRef "

应该是

SELECT b FROM BasicAccountAudit as b WHERE b.id.accountRef  = :accountRef "

在第二个查询中,您没有声明别名,因此默认情况下它将在您的对象下查找ID。