JPA中的动态查询(按示例查询)

时间:2017-04-09 20:29:51

标签: java postgresql hibernate jpa

我有这些结构:

public class Invoice {
    @Id
    @GeneratedValue(strategy = AUTO)
    private Long id;

    @JoinColumn(name = "customer_id")
    @OneToOne(targetEntity = Customer.class)
    private Customer customer;

    @JoinColumn(name = "address_id")
    @OneToOne(targetEntity = Address.class)
    private Address address;
    private String invoiceType;
    // getters and setters
}

public class Customer {
    @Id
    @GeneratedValue(strategy = AUTO)
    private Long id;
    private String name;
    // getters and setters
}

public class Address {
    @Id
    @GeneratedValue(strategy = AUTO)
    private Long id;
    private String city;
    private String state;
    private String country;
    @ManyToOne
    @JoinColumn(name = "customer_id")
    @JsonIgnore
    private Customer customer;
    // getters and setters
}

InvoiceRepository是这样的:

public interface InvoiceRepository extends JpaRepository<Invoice, String> {
    List<Invoice> findByCustomerIdAndAddressId(long customerId, long addressId);
    List<Invoice> findByCustomerId(long customerId);
    List<Invoice> findByCustomerIdAndInvoiceType(long customerId, String invoiceType);
}

它在InvoiceService上自动装配的存储库。

我已经阅读过“按示例查询”,但我不确定是否可以将其与JPA一起使用。我可以在没有Hibernate的情况下使用吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你误解了JPA和Hibernate。

为了澄清,JPA是一个规范。 JPA代表Java Persistence API。它有各种实现 - 所谓的提供程序 - ,例如OpenJPA,EclipseLink,Hibernate等。

想象一下这就像拥有大量接口 - 基本上就是API - 并且你没有实现它们。这是JPA。

接口的实现由提供者完成,例如Hibernate。

当然,您可以在没有Hibernate提供程序的情况下使用JPA,但是您必须使用另一个(EclipseLink,OpenJPA等)。