【问题标题】:How to write JPA join?JPA加入怎么写?
【发布时间】:2019-01-15 09:08:49
【问题描述】:

我有两张表 Product 和 Price。产品可以有多个价格,具体取决于时间段。

产品实体:

@Entity
public class Product {

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

String name;

@OneToMany(mappedBy = "product", fetch = FetchType.EAGER)

List<Price> price;

}

价格实体:

@Entity
public class Price {

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

LocalDate timePeroid;

Double price;

@ManyToOne()
Product product;
}

我想要 3 个动态日期中的时间段的产品实体。但如果时间段不存在,那么我也应该有产品实体,但标价应该包含三个空值。我如何在 JPA 中编写查询。?

【问题讨论】:

    标签: spring spring-boot jpa spring-data-jpa spring-data


    【解决方案1】:

    您可以使用 JpaRepository 或 EntityManagerFactory 来查询 JPA 中的数据。

    1. JpaRepository
    您可以为您的产品实体创建存储库,如下所示。

    @Repository
    public interface ProductRepository extends JpaRepository<Product, Long> {
    
    }
    

    然后在您的存储库的依赖注入之后。

     @Resource
     ProductRepository productRepository;
    

    您可以使用此存储库来获取所需的产品,例如。

     Product product = productRepository.findById(id);
    

    2。 EntityManagerFactory

    EntityManagerFactory 依赖注入后

     @Resource
     EntityManagerFactory entityManagerFactory;
    

    你可以像这样检索数据。

     EntityManager entityManager = entityManagerFactory.createEntityManager();
     Product product =  entityManager.find(Product.class, id)
    

    在上述两种情况下,如果它们保存在数据库中,结果产品将包含其价格列表,否则列表将为空。

    对于加入特殊条件,您可以查看在实体管理器工厂和 Jpa 存储库中编写自定义查询的方式,以下链接可能对您有所帮助。

    https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-three-custom-queries-with-query-methods/

    https://docs.oracle.com/javaee/6/tutorial/doc/bnbrg.html

    【讨论】:

      【解决方案2】:

      您已经在产品中以列表形式获取价格对象。我同意,如果你想要一个只需要一个价格的特殊情况,你可以写一个查询。另一种方法是编写一个“getCurrentPrice(Date d)”方法。 (没有参数的第二个版本将使用“今天”作为日期)。您将日期与每个价格的日期范围进行比较,然后从列表中返回正确的价格。无论列表中有多少价格,这可能就是您想要在代码中调用的价格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-14
        • 2021-08-09
        • 1970-01-01
        • 2012-05-21
        • 2017-09-04
        • 2021-11-05
        • 2013-11-10
        • 1970-01-01
        相关资源
        最近更新 更多