当我使用外键搜索实体及其记录时遇到问题。按照业务逻辑,我需要搜索Entity-LookupRequest表,该帐户具有帐户(帐户ID不为null)和外键=“ callback”(具有null)。
请注意,帐户ID不是唯一的(为简单起见,我删除了表中的其他参数以使其简短)。过滤记录后,必须将LookupRequest.callBack更新为Foreignkey条目。当外键为空时,我无法检索记录。
import javax.persistence.*;
@Entity
public class LookupRequest {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
@Column
private String account;
@Column
private String caseId;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "id", unique=false, nullable=true, updatable=true)
private Callback callback;
public LookupRequest(String account, String caseId) {
this.account = account;
this.caseId = caseId;
callback = null;
}
public Long getId() {
return id;
}
public String getAccount() {
return account;
}
public String getCaseId() {
return caseId;
}
public Callback getCallback() {
return callback;
}
public void setCallback(Callback callback) {
this.callback = callback;
}
}
@Repository
public interface LookupRequestRepository extends JpaRepository<LookupRequest, Long> {
@Query("SELECT lr from LookupRequest lr where lr.account = :account and lr.callback = :callback")
LookupRequest findCaseId(@Param("account") String account, @Param("callback") String callback);
}
@Getter
@Setter
@Entity
public class Callback {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
public Long id;
@Column(length = 20000)
private String rawResponse;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setRawResponse(String rawResponse) {
this.rawResponse = rawResponse;
}
}
然后我打电话如下:
LookupRequest lookupRequestFromDB = lookupRequestRepository.findCaseId("ABC", null);
出了什么问题?
答案 0 :(得分:0)
NULL不等于任何东西,您需要使用“ is NULL”。 参见here
在您的情况下:
SELECT lr from LookupRequest lr where lr.account = :account and (lr.callback = :callback or lr.callback is null)