首页 > 解决方案 > JavaSpring中的SQL查询返回Null

问题描述

我正在尝试通过 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...
}

标签: javarestspring-bootjpajpql

解决方案


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

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

应该

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

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


推荐阅读