我有两个表产品和价格。产品可以有多个价格,具体取决于时间段。
产品实体:
@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 中为此编写查询。?
您可以使用 JpaRepository 或 EntityManagerFactory 在 JPA 中查询数据。
1. Jpa存储库 您可以为您的产品实体创建存储库
,如下所示。
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
然后在存储库的依赖注入之后。
@Resource
ProductRepository productRepository;
您可以使用此存储库来获取所需的产品,例如。
Product product = productRepository.findById(id);
2. 实体经理工厂
在实体管理器工厂的依赖注入之后
@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
您已经将价格对象作为产品中的列表获取。我同意,如果您想要一个只需要一个价格的特殊情况,您可以编写一个查询。另一种方法是编写一个'getCurrentPrice(Date d(方法。(没有参数的第二个版本将使用"今天"作为日期(。您将日期与每个价格的日期范围进行比较,并从列表中返回正确的价格。无论列表中有多少价格,这都可能是您希望在代码中调用的价格。