Joing two tables in JPA repository
I am going throw spring boot tutorial and got this requriment
@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.
My Second Model class
@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;
In the same way I have created different controller and two differnt JPA repository to fetch the data from the each table and working fine.
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>{
}
Model class for product
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>{
}
Now I got the secanrio where I need to join these two tables.
MySql command
SELECT transiction.user_id, transiction.quantity,transiction.product_name, transiction.Price,product.LTP
FROM product
INNER JOIN transiction
ON product.product=transiction.product_name;
I can see propper data in sql. But I dont know how to write this query in Java code.
I am going throw this tutorial https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections but not getting much idea.
this is what I am trying in my repositry
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")
}
but no luck because i m not storing this into some list or maybe something else not sure.
I have question
- Do I need to write service class or something like that.
Can anybody help me here.