Spring Data JPA - how to make intermediate query in spring data jpa - spring

I have Promotion, PromotionDetail, Product entities like this:
#Entity
#Table(name = "promotions")
public class Promotion implements Serializable {
#Id
private String id;
#OneToMany(
fetch = FetchType.LAZY,
mappedBy = "promotion",
cascade = CascadeType.ALL
)
private Collection<PromotionDetail> promotionDetails;
}
====
#Entity
#Table(name="product")
public class Product implements Serializable {
#Id
private String id;
#OneToMany(
mappedBy = "product"
)
private Collection<PromotionDetail> promotionDetails;
}
====
#Entity
#Table(name = "promotion_details")
public class PromotionDetail implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#ManyToOne
#JoinColumn(
name = "promotion_id",
referencedColumnName = "id",
nullable = false
)
#JsonIgnoreProperties("promotionDetails")
private Promotion promotion;
#ManyToOne
#JoinColumn(
name = "product_id",
referencedColumnName = "id",
nullable = false
)
#JsonIgnoreProperties({"promotionDetails"})
private Product product;
}
from the above entities i want to find a solution at ProductRepository to get list of Products based on Promotion Id
i tried with line of code like this but it doesn't work:
Page<Product> findProductsByPromotionDetails_Promotion_Id(long id, Pageable pageable);
can someone please help me
it's pretty simple right
Examples of data are as follows:
Product:
id
--------------
P0882021035821
P0882021035822
P0882021035823
P1482022025430
Promotion:
id discount
-------
1 12
2 13
3 12
Promition_Detail
id product_id promiotion_id
1 P0882021035821 1
2 P0882021035823 1
3 P1482022025322 1
4 P1482022025430 5
5 P1482022025322 5
when i execute above query to get list product with promotion _id = 1 I have a product list that has product_id like:
P0882021035821
P0882021035823
P1482022025322
P1482022025322
the issue is i have double product have product id equals P1482022025322
and the result I want is a list like this:
P0882021035821
P0882021035823
P1482022025322
when I execute : findProductsByPromotionDetails_Promotion_Id(1,1);

Related

Entity A has OneToOne relation with Entity B, when a data is inserted in A, entity B also gets inserted the same id as A

So, I have a Student entity and a ShoppingCart entity.
What I wanted to achieve is, when I insert data for student, let's say studentId = 1, the cartId automatically has 1 inserted. For example:
Student table
student_id
full_name
1
Foo
2
Bar
When these 2 students are created, the shopping cart table automatically becomes:
Shopping cart table
cart_id
1
2
These are my Student and Cart entities.
Student.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "student", uniqueConstraints = {
#UniqueConstraint(name = "uc_student_email_address", columnNames = {"email_address"})
public class Student {
#Id
#SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize=1
)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "student_sequence")
private Long studentId;
private String fullName;
#Column(name = "email_address", nullable = false)
private String email;
private String username;
private String password;
ShoppingCart.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
public class ShoppingCart {
#Id
private Long cartId;
#OneToOne
#MapsId
#JoinColumn(name = "cart_id", referencedColumnName = "studentId")
private Student student;
So, how do I achieve this?
Thanks in advance.

Spring Boot JPA Fetch Parent & Child

I have 2 tables:
#Entity
#Table
public class ProductEntity extends AbstractEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long productId;
#OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<ProductItemEntity> productItems;
}
#Entity
#Table
public class ProductItemEntity extends AbstractEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long itemId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "PRODUCT_ID", nullable = false)
private ProductEntity product;
#Column(name="PRODUCT_RATE") // Unique
private Integer productRate;
}
I am trying to run a test where I am querying by productId and productRate, which is as follow:
#Query("SELECT p FROM ProductEntity p JOIN FETCH p.productItems pi WHERE p.productId = :productId AND pi.productRate = :rate ")
ProductEntity findByProductAndRate(#Param("productId") Long productId, #Param("rate") Integer rate);
I save a product and product item first. Then execute above method to get the product with product item. But I get null result.
Don't know if I am missing something. Any help would be appreciated.
Spring Boot
H2 (#DataJpaTest)

Spring JPA Self Reference Issue

I created a table, Category in Postgres which holds both parent and child categories and references to itself (it's a self join table)
The table comprises of following columns: id, parent_id, start_date, end_date, status
I also have one row for root parent whose id = 0. So, any first level categories have root as its parent.
Example: Apparel > Women. Here Apparel(id=1) is a first level category whose parent_id = 0. Women is another category whose parent_id = 1.
I am using Spring JpaRepository findAll on my table and this is leading to infinite recursion.
POJO
#Table(name = "ofr_category")
#Getter
#Setter
#NoArgsConstructor
public class Category {
#Id
#Column(name = "cat_id", updatable = true, unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CATEGORY_SEQ")
#SequenceGenerator(sequenceName = "CATEGORY_ID_SEQ", allocationSize = 1, name = "CATEGORY_SEQ")
private Long id;
#Column(name = "cat_name")
private String name;
#Column(name = "cat_status")
private String status;
#Column(name = "start_date")
private LocalDate startDate;
#Column(name = "end_date")
private LocalDate endDate;
#Column(name = "parent_id")
private Long parentId;
#JsonBackReference
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "parent_id", insertable = false, updatable = false)
private Category parentCategory;
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "parentCategory")
private List<Category> childCategories;
public Category getParentCategory(){
return parentCategory;
}
}
Exception seen
"Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Direct self-reference leading to cycle (through reference chain: java.util.ArrayList[0]->com.test.category.dataobject.Category[\"parentCategory\"]->com.test.category.dataobject.Category[\"parentCategory\"]->com.test.category.dataobject.Category[\"parentCategory\"])",
Maybe you can have a look into #JsonIdentityInfo, which solved a similar problem for me. You can check if this basic annotation works for you.:
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Category {
...
}

Inner join on two tables in spring boot

I have 2 entities and want to perform an inner join on the ID of these two tables. How do I do that? After joining the tables, how do I get the values?
First entity: Employee.java
#Entity
#Table(name = "emp")
public class Employee {
#Id
#Column(name = "id", nullable = false)
private int id;
#Column(name = "language", nullable = false)
private String language;
Second entity: Username.java
#Entity
#Table(name = "users")
public class Username {
#Id
#Column(name = "id", nullable = false)
private int id;
#Column(name = "name", nullable = false)
private String name;
Thanks
I don't know it's helpful for your or not but,
You have to give relationship between those table first(Here i defined bidirectional relationship).
I suppose there is #OneToOne mapping. As like follow,
In Employee Table,
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "username_id")
private Username username;
#OneToOne(mappedBy = "employee")
private Employee employee;
Same way whenever you need those data base on requirement then Place Query as following way in your Employee Repository,
#Query(nativeQuery = true, value="<your-join-query>")
public Employee getEmployeeAllDetails();
For more brief detail follow this kind of tutorials which give you better idea regurding working mechenisum.
https://howtodoinjava.com/
https://www.baeldung.com/

Hibernate Formula with join

i have an entity order and an entity order_items ( 1->n relation).
I want a field in order that table that show the sum(quantity) of related order items. These are my entities:
#Entity(name="ORDERS")
public class Order {
#Id
#GeneratedValue
#Column (name="order_id")
private long id;
#OneToOne
#JoinColumn(name="customer_id")
private Customer customer;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "order", cascade =CascadeType.ALL)
#JsonManagedReference
private List<OrderItem> orderItems=new ArrayList();
#Entity(name="ORDER_ITEMS")
public class OrderItem {
#Id
#GeneratedValue
#Column (name="order_item_id")
private long id;
#Column (name="quantity")
private int quantity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "order_id", nullable = false)
#JsonBackReference
private Order order;
I want a new field in Order entity that show the total quantity ( sum of quantity of the childs).
I've tried to add the field in order but it not works
#Formula("select sum(oi.quantity) from ORDER_ITEMS oi where oi.order_id= order_id)")
private int totalQuantity;
Can you help me to fix it ?
The solution
#Formula("(select sum(oi.quantity) from ORDER_ITEMS oi where oi.order_id= order_id)")
private int totalQuantity;

Resources