【发布时间】:2021-09-13 15:38:20
【问题描述】:
在 JPA 存储库中连接两个表
我要抛出 spring boot 教程并得到这个要求
@Entity
@Table(name = "transiction")
public class Transictions {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@Column(name = "userId")
private Long userId;
@Column(name = "productName")
private String productName;
@Column(name = "quantity")
private int quantity;
@Column(name = "price")
private double price;
@Column(name = "transictionDate")
private Date transictionDate;
// Getter and Setter method with constructor.
我的第二个模型课
@Entity
@Table(name = "product")
public class product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "product")
private String productName;
@Column(name = "ltp")
private float LTP;
@Column(name = "exchange")
private String exchange;
以同样的方式,我创建了不同的控制器和两个不同的 JPA 存储库来从每个表中获取数据并且工作正常。
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.springboot.Ole.Model.Transictions;
public interface TransictionRepository extends JpaRepository<Transictions, Long>{
}
产品的模型类
package com.springboot.Ole.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.springboot.Ole.Model.Product;
@Repository
public interface ProducttRepository extends JpaRepository<Instrument, Long>{
}
现在我得到了需要加入这两个表的 secanrio。
MySql 命令
SELECT transiction.user_id, transiction.quantity,transiction.product_name, transiction.Price,product.LTP
FROM product
INNER JOIN transiction
ON product.product=transiction.product_name;
我可以在 sql 中看到适当的数据。但是我不知道如何用 Java 代码编写这个查询。
我打算抛出这个教程https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections,但没有太多想法。
这就是我在我的存储库中尝试的内容
package com.springboot.Ole.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.springboot.Ole.Model.Transictions;
public interface TransictionRepository extends JpaRepository<Transictions, Long>{
@Query(value = "SELECT transiction.user_id, transiction.quantity,transiction.product_name, transiction.Price,product.LTP"
+ "FROM product"
+ "INNER JOIN transiction"
+ "ON product.product=transiction.product_name")
}
但没有运气,因为我没有将它存储到某个列表中,或者其他不确定的东西。
我有问题
- 我是否需要编写服务类或类似的东西。
谁能帮帮我。
【问题讨论】:
-
您必须使用
@OneToMany和@ManyToOne在模型类中显式定义连接映射 -
@Mr_Thorynque 我已经完成了,我可以看到库也在 mysql 中创建。现在想知道如何获取数据。
标签: java mysql spring spring-boot jpa