代码之家  ›  专栏  ›  技术社区  ›  meGaMind

如何编写JPA join?

  •  0
  • meGaMind  · 技术社区  · 8 年前

    我有两张产品和价格表。根据时间段,产品可以有多种价格。

    产品实体:

    @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中为这个编写查询。?

    2 回复  |  直到 8 年前
        1
  •  0
  •   Muneeb Shahid    8 年前

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

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

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

    然后在对存储库进行依赖注入之后。

     @Resource
     ProductRepository productRepository;
    

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

     Product product = productRepository.findById(id);
    

    2.实体管理工厂

    在EntityManagerFactory的依赖项注入之后

     @Resource
     EntityManagerFactory entityManagerFactory;
    

    你可以像这样检索数据。

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

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

    对于加入特殊条件,您可以查看entity manager factory和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
  •  0
  •   Mafuj Shikder    7 年前

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