在存储库中一对一休眠无效查询

时间:2018-10-05 13:18:02

标签: java hibernate spring-data-jpa hql

目前,我通过本机查询解决了此问题,我也知道可以通过以下查询解决此问题:

(first use cross join)
@Query("select s from SendingApplication s where s.sftpAccess.id is not null")
(second use left outer join)
@Query("select s from SendingApplication s left join s.sftpAccess sa where sa is not null") 

但是看起来不太好。

我有2个实体:

@Entity
@Getter
@Setter
@Table(name = "sending_application")
public class SendingApplication {
    @Id
    @GeneratedValue
    private Integer id;

    @OneToOne(mappedBy = "sendingApplication", fetch = FetchType.LAZY)
    private SftpAccess sftpAccess;
}

@Entity
@Getter
@Setter
@Table(name = "sftp_access")
public class SftpAccess {
    @Id
    @GeneratedValue
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name="sending_application",
            referencedColumnName = "id",
            insertable = false,
            updatable = false
    )
    private SendingApplication sendingApplication;
}

我可以加载发送应用程序,然后访问字段sftpAccess,它包含所有数据。但是我有存储库:

@Repository
public interface SendingApplicationDao extends AbstractDao<SendingApplication> {

    @Query("select s from SendingApplication s where s.sftpAccess is not null")
    List<SendingApplication> loadSftpApplications();
}

和loadSftpApplications方法使用此查询-

SELECT
    sendingapp0_.id AS id1_9_
FROM
    sending_application sendingapp0_
WHERE
    (sendingapp0_.id IS NOT NULL)

我希望看到

SELECT
    sendingapp0_.id AS id1_9_
FROM
    sending_application sendingapp0_
    left join sftp_access on sftp_access.sending_application = sendingapp0_.id
WHERE
    (sftp_access.id IS NOT NULL)

我做错了什么?

数据库:

CREATE TABLE `sending_application` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `sftp_access` (
`id`  int(11) NOT NULL AUTO_INCREMENT ,
`sending_application`  int(11) NULL ,
FOREIGN KEY (`sending_application`) REFERENCES `sending_application` (`id`),
PRIMARY KEY (id)
);

0 个答案:

没有答案