【问题标题】:Spring Data JPA how to specify Join type or Fetch Mode when using get("property") chain vs JoinSpring Data JPA如何在使用get(“property”)链与Join时指定Join类型或Fetch Mode
【发布时间】:2021-09-24 23:44:54
【问题描述】:

我有两个(基于 Hibernate 的)Spring Data JPA 域类,“One”端 Customer.class:

@Entity
@Table(name = "sys_customer")
@Data
public class Customer implements Serializable {
    @Id
    @Column(name = "cust_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "cust_name")
    private String customerName;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    private Set<Order> orders;

}

和“多”端 Order.class:

@Entity
@Table(name = "sys_order")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Order implements Serializable {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "order_name")
    private String orderName;

    @ManyToOne
    @JoinColumn(name = "order_cust_id", referencedColumnName = "cust_id")
    private Customer customer;

    public Order( String orderName) {
        this.orderName = orderName;
    }

    public Order(String orderName, Customer customer) {
        this.orderName = orderName;
        this.customer = customer;
    }
}

我有 OrderRepository 接口,它扩展了 JpaRepository 接口和 JpaSpecificationExecutor 接口:

public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {
}

我有一个带有静态方法 searchByCustomerName 的 OrderSpecification.class:

public class OrderSpecification {
    public static Specification<Order> searchByCustomerName(String customerName) {
        return new Specification<Order>() {
            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Join<Order, Customer> join = root.join("customer");
                return criteriaBuilder.like(join.get("customerName"), "%" + customerName + "%");
                //return criteriaBuilder.like(root.get("customer").get("customerName"), "%" + customerName + "%");
            }
        };
    }
} 

为了找到get("property")链和Join的区别,我写了一个简单的测试方法,把上面的OrderSpecificatin.class代码注释掉

    @Test
    @Transactional
    public void testFindOrderByCustomerName(){
        String name = "adam";
        List<Order> orders = orderRepository.findAll(OrderSpecification.searchByCustomerName(name));
        for(Order order: orders){
            Customer customer = order.getCustomer();
            log.info(new StringBuilder().append(customer.getId()).append(" ").append(customer.getCustomerName()).toString());

        }
    }

我发现: get("property") 链使用交叉连接(性能非常差),而 Join 使用内部连接(因为 ManyToOne() 默认为 Fetch= FetchType.EAGER)

/* get("property") chain: Hibernate: select order0_.order_id as order_id1_1_, order0_.order_cust_id 为 order_cu3_1_, order0_.order_name as order_na2_1_ from sys_order order0_ 交叉连接 sys_customer customer1_ where order0_.order_cust_id=customer1_.cust_id 和 (customer1_.cust_name like ?) Hibernate: select customer0_.cust_id 作为 cust_id1_0_0_,customer0_.cust_name 作为 cust_nam2_0_0_ 来自 sys_customer customer0_ where customer0_.cust_id=? */

/** * "Join": * Hibernate: 选择 order0_.order_id 作为 order_id1_1_, order0_.order_cust_id 为 order_cu3_1_,order0_.order_name 为 order_na2_1_ from sys_order order0_ 内联 sys_customer customer1_ 在 order0_.order_cust_id=customer1_.cust_id 上 customer1_.cust_name 喜欢 ? * 休眠:选择 customer0_.cust_id 作为 cust_id1_0_0_, customer0_.cust_name 作为 cust_nam2_0_0_ 来自 sys_customer customer0_ customer0_.cust_id=? */

我的问题是:

  1. 在使用get("property") 链式方法时,是否可以指定 Join 类型(内部,所有三个外部)或 Fetch 类型(LAZY,EAGER)以避免交叉连接?
  2. 我应该使用 get("chain") 还是始终留在 Join 中?
  3. 采用静态方法的 OrderSpecification.class 方法是否遵循良好的 OOP 设计模式?

【问题讨论】:

    标签: java spring-boot hibernate oop jpa


    【解决方案1】:

    您不能指定路径的连接类型。默认情况下,它将使用 INNER 连接语义,这是 JPA 规范要求的。如果您想要不同的连接类型,则必须显式创建连接。使用get 呈现为交叉连接的事实是Hibernate 旧查询模型的限制,但Hibernate 6.0 将解决这个问题。虽然语义是相同的,但数据库的查询规划器应该能够以相同的方式处理这两个查询。也许您只需要更新您的数据库版本?

    没有“最佳实践”,即这实际上取决于您的需求。显式连接就是这样,显式的。所以多次调用join 会在 SQL 中创建多个连接。

    至于 OOP 问题,我认为这很好,是的。

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2021-12-19
      • 1970-01-01
      • 2019-10-01
      • 2017-09-29
      • 2013-06-30
      相关资源
      最近更新 更多