unbale使用Reporsitory中的@Query在spring数据jpa中形成正确的连接查询

时间:2015-10-18 13:00:31

标签: spring spring-mvc spring-data spring-data-jpa

我是Spring Data Jpa的新手,能够在单个表上使用正确的函数名来获得结果。但是现在我面临着基于连接得到结果的问题。我有两个表发票表(列:accountNumber,courierId),帐户表(列:数字,clinetId)。现在我需要加入这两个表并获得基于courierId和clientId的Invoice结果。所以在存储库中我已经形成了如下所示的查询:

@Query("select Invoice from Invoice i left join Account a on i.accountNumber = a.number where i.courierId=?1 and a.clientId=?2")    
    List<Invoice> findByCourierIdAndClientId(Long courierId, Long clientId);

但是我的调试日志中出现以下错误:

[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  Path expected for join!
[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  Path expected for join!
antlr.SemanticException: Path expected for join!

[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  Invalid path: 'a.clientId'
[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  Invalid path: 'a.clientId'
org.hibernate.hql.internal.ast.InvalidPathException: Invalid path: 'a.clientId'

[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  left-hand operand of a binary operator was null
[ERROR] org.hibernate.hql.internal.ast.ErrorCounter -  left-hand operand of a binary operator was null
antlr.SemanticException: left-hand operand of a binary operator was null

在Account表中我在mysql表和Account.java中有client_id字段,我有

@ManyToOne
private Client client;

public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

如果我使用建议的解决方案,

@Query("SELECT i from Invoice i WHERE i.courierId =?1 AND i.clientId =?2")
List<Invoice> findByCourierIdAndClientId(Long courierId, Long clientId);

我收到以下错误:

 java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: clientId of: com.trace.domain.Invoice [SELECT i from com.trace.domain.Invoice i WHERE i.courierId =?1 AND i.clientId =?2]

以下是我的映射:

在Account.java中,

 @OneToMany(mappedBy = "account")
 @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
 private Set<Invoice> invoices = new HashSet<>();

在Invoice.java中,

 @ManyToOne   
 private Account account;

我需要在这些映射中进行任何更改。而且在解决方案中

@Query("SELECT i from Invoice i WHERE i.courierId =?1 AND i.clientId =?2")

我不遵循发票表如何仅通过帐户获取已加入的详细信息,而且发票表中没有i.clientIdclientId仅出现在帐户表中。

以下是我的Invoice.java

/**
 * A Invoice.
 */
@Entity
@Table(name = "invoice")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Invoice implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    @Column(name = "account_number")
    private String accountNumber;

    @Column(name = "invoice_number")
    private String invoiceNumber;

    @Column(name = "invoice_amount")
    private Double invoiceAmount;

    @Column(name = "status")
    private String status;

    @Column(name = "edi_number")
    private String ediNumber;

    @Column(name = "bill_date")
    private Date billDate;

    @Column(name = "courier_id")
    private Long courierId;

 // @JoinColumn(name="owner_id", nullable=false)

    @ManyToOne   
    private Account account;



    @OneToMany(mappedBy = "invoice")
    //@JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<InvoiceDetails> invoiceDetailss = new HashSet<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getInvoiceNumber() {
        return invoiceNumber;
    }

    public void setInvoiceNumber(String invoiceNumber) {
        this.invoiceNumber = invoiceNumber;
    }

    public Double getInvoiceAmount() {
        return invoiceAmount;
    }

    public void setInvoiceAmount(Double invoiceAmount) {
        this.invoiceAmount = invoiceAmount;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getEdiNumber() {
        return ediNumber;
    }

    public void setEdiNumber(String ediNumber) {
        this.ediNumber = ediNumber;
    }


        public Date getBillDate() {
            return billDate;
        }

        public void setBillDate(Date billDate) {
            this.billDate = billDate;
        }

        public Long getCourierId() {
            return courierId;
        }

        public void setCourierId(Long courierId) {
            this.courierId = courierId;
        }

        public Account getAccount() {
            return account;
        }

        public void setAccount(Account account) {
            this.account = account;
        }

    public Set<InvoiceDetails> getInvoiceDetailss() {
        return invoiceDetailss;
    }

    public void setInvoiceDetailss(Set<InvoiceDetails> invoiceDetailss) {
        this.invoiceDetailss = invoiceDetailss;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Invoice invoice = (Invoice) o;

        if ( ! Objects.equals(id, invoice.id)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }

    @Override
    public String toString() {
        return "Invoice{" +
                "id=" + id +
                ", accountNumber='" + accountNumber + "'" +
                ", invoiceNumber='" + invoiceNumber + "'" +
                ", invoiceAmount='" + invoiceAmount + "'" +
                ", ediNumber='" + ediNumber + "'" +
                ", status='" + status + "'" +
                ", billDate='" + billDate + "'" +
                ", courierId='" + courierId + "'" +
                '}';
    }
}

以下是我的Account.java,

/**
 * Account.
 */
@Entity
@Table(name = "account")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Account implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    @Column(name = "number", nullable = false)
    private String number;

    @NotNull
    @Column(name = "name")
    private String name;

    @Column(name = "currency_code")
    private String currencyCode;

    @Column(name = "edi_type")
    private String ediType;

    @Column(name = "is_fedex_express_gsr")
    private Boolean isFedexExpressGsr;

    @Column(name = "is_fedex_ground_gsr")
    private Boolean isFedexGroundGsr;

    @Column(name = "is_ups_gsr")
    private Boolean isUpsGsr;

    @Column(name = "electronic_voiding")
    private Boolean electronicVoiding;

    @Column(name = "activate_signature_service")
    private Boolean activateSignatureService;

    @Column(name = "reject_invoices")
    private Boolean rejectInvoices;

    @Column(name = "notify_client_services")
    private Boolean notifyClientServices;

    @Column(name = "is_active")
    private Boolean isActive;

    @Column(name = "address")
    private String address;

    @Column(name = "city")
    private String city;

    @Column(name = "state")
    private String state;

    @Column(name = "postal_code")
    private String postalCode;


    @OneToMany(mappedBy = "account")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Invoice> invoices = new HashSet<>();



    @ManyToOne
    private Courier courier;

    @ManyToOne
    private Client client;

    @ManyToMany
    @JoinTable(
            name = "account_group_members",
            joinColumns = {@JoinColumn(name = "account_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id", referencedColumnName = "id")})
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<AccountGroup> accountGroups = new HashSet<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCurrencyCode() {
        return currencyCode;
    }

    public void setCurrencyCode(String currencyCode) {
        this.currencyCode = currencyCode;
    }

    public String getEdiType() {
        return ediType;
    }

    public void setEdiType(String ediType) {
        this.ediType = ediType;
    }

    public Boolean getIsFedexExpressGsr() {
        return isFedexExpressGsr;
    }

    public void setIsFedexExpressGsr(Boolean isFedexExpressGsr) {
        this.isFedexExpressGsr = isFedexExpressGsr;
    }

    public Boolean getIsFedexGroundGsr() {
        return isFedexGroundGsr;
    }

    public void setIsFedexGroundGsr(Boolean isFedexGroundGsr) {
        this.isFedexGroundGsr = isFedexGroundGsr;
    }

    public Boolean getIsUpsGsr() {
        return isUpsGsr;
    }

    public void setIsUpsGsr(Boolean isUpsGsr) {
        this.isUpsGsr = isUpsGsr;
    }

    public Boolean getElectronicVoiding() {
        return electronicVoiding;
    }

    public void setElectronicVoiding(Boolean electronicVoiding) {
        this.electronicVoiding = electronicVoiding;
    }

    public Boolean getActivateSignatureService() {
        return activateSignatureService;
    }

    public void setActivateSignatureService(Boolean activateSignatureService) {
        this.activateSignatureService = activateSignatureService;
    }

    public Boolean getRejectInvoices() {
        return rejectInvoices;
    }

    public void setRejectInvoices(Boolean rejectInvoices) {
        this.rejectInvoices = rejectInvoices;
    }

    public Boolean getNotifyClientServices() {
        return notifyClientServices;
    }

    public void setNotifyClientServices(Boolean notifyClientServices) {
        this.notifyClientServices = notifyClientServices;
    }

    public Boolean getIsActive() {
        return isActive;
    }

    public void setIsActive(Boolean isActive) {
        this.isActive = isActive;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public Courier getCourier() {
        return courier;
    }

    public void setCourier(Courier courier) {
        this.courier = courier;
    }

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public Set<Invoice> getInvoices() {
        return invoices;
    }

    public void setInvoices(Set<Invoice> invoices) {
        this.invoices = invoices;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Account shipper = (Account) o;

        if (!Objects.equals(id, shipper.id))
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }

    @Override
    public String toString() {
        return "Shipper{" + "id=" + id + ", number='" + number + "'" + ", name='" + name + "'" + ", currencyCode='"
                + currencyCode + "'" + ", ediType='" + ediType + "'" + ", isFedexExpressGsr='" + isFedexExpressGsr + "'"
                + ", isFedexGroundGsr='" + isFedexGroundGsr + "'" + ", isUpsGsr='" + isUpsGsr + "'"
                + ", electronicVoiding='" + electronicVoiding + "'" + ", activateSignatureService='"
                + activateSignatureService + "'" + ", rejectInvoices='" + rejectInvoices + "'"
                + ", notifyClientServices='" + notifyClientServices + "'" + ", isActive='" + isActive + "'"
                + ", address='" + address + "'" + ", city='" + city + "'" + ", state='" + state + "'" + ", postalCode='"
                + postalCode + "'" + '}';
    }
}

在InvoiceRepository.java中输入以下内容后,

@Query("from Invoice i " + " where i.courierId = :courierId " + " and i.account.client.id = :clientId ")
    List<Invoice> findByCourierIdAndClientId(@Param("courierId") Long courierId, @Param("clientId") Long clientId);

我没有收到任何错误,但我从mysql数据库获取任何结果集。我的调试日志如下:

[DEBUG] com.sample.aop.logging.LoggingAspect - Enter: com.sample.web.rest.InvoiceResource.getInvoicesByCourierIdAndClientId() with argument[s] = [1, 1]
[DEBUG] com.sample.web.rest.InvoiceResource - REST request to get Invoices  By Courier Id and Client Id 1  1
[DEBUG] com.sample.aop.logging.LoggingAspect - Enter: com.sample.service.InvoiceService.findByCourierIdAndClientId() with argument[s] = [1, 1]
[DEBUG] com.sample.aop.logging.LoggingAspect - Exit: com.sample.service.InvoiceService.findByCourierIdAndClientId() with result = []
[DEBUG] com.sample.aop.logging.LoggingAspect - Exit: com.sample.web.rest.InvoiceResource.getInvoicesByCourierIdAndClientId() with result = []

在InvoiceResource.java中,我有以下映射:

// Get Invoices By Courier Id and CustomerId
    @RequestMapping(value = "/invoices/byCourierAndClient", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public List<Invoice> getInvoicesByCourierIdAndClientId(@RequestParam(value = "courierId") Long courierId,
            @RequestParam(value = "clientId") Long clientId) {
        log.debug("REST request to get Invoices  By Courier Id and Client Id " + courierId + "  " + clientId);
        return invoiceService.findByCourierIdAndClientId(courierId, clientId);
    }

Client.java中的Id字段如下:

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

以下查询我用于在mysql数据库表上手动验证我的数据,该表返回包含记录的结果集。

select * from invoice i, account a where i.account_number = a.number
and i.courier_id = 1
and a.client_id = 1

2 个答案:

答案 0 :(得分:1)

简要介绍一下您的代码似乎表明您已经在InvoiceAccount之间建立了正确的关系映射。在JPQL / HQL中,您不通过提供连接条件来加入SQL。所以你的查询应该是

@Query("from Invoice i "
      + " where i.courierId = :courierId "
      + " and i.account.client.id = :clientId ")
List<Invoice> findByCourierIdAndClientId(@Param("courierId") Long courierId, 
                                         @Param("clientId") Long clientId);

(假设Client中的ID字段被称为id

看起来很直观吗?

而且,鉴于您的查询非常简单,您甚至可以通过正确命名您的finder方法让Spring Data生成您的查询:

// no more @Query needed, works magically
List<Invoice> findByCourierIdAndAccountClientId(Long courierId, Long clientId);

答案 1 :(得分:0)

你可以尝试这样的事情。如果正确映射了关系(@ OneToMany / ManyToOne),则无需显式连接表。

@Query("SELECT i from Invoice i WHERE i.courierId =?1 AND i.clientId =?2")
List<Invoice> findByCourierIdAndClientId(Long courierId, Long clientId);

您甚至可以直接将对象传递给查询,例如

@Query("SELECT i from Invoice i WHERE i.courierId= :courier AND i.clientId = :client")
List<Invoice> findByCourierAndClient(@Param("courier") Courier courier, @Param("client") Client client);