Products with productName in the format “product1”, “product2”, “product3” … “product1000” are stored in the database.
If SearchQuery is “product”, there will be 1000 hibernate select queries.
Product.java
@Entity
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Table(name = "tbl_product", indexes = {@Index(name = "idx_pname", columnList = "pname")})
@EntityListeners(AuditingEntityListener.class)
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long pno;
private String pname;
private int price;
private String pdesc;
private boolean delFlag;
private Long categoryNum;
@CreatedDate
private LocalDateTime date;
@Builder.Default
private Long viewCount= Long.valueOf(0);
@ManyToOne(fetch = FetchType.EAGER)
private User seller;
@ElementCollection(fetch = FetchType.LAZY)
@Builder.Default
private List<ProductImage> imageList = new ArrayList<>();
public void changePrice(int price) {
this.price = price;
}
public void changeDesc(String desc) {
this.pdesc = desc;
}
public void changeName(String name) {
this.pname = name;
}
public void addImage(ProductImage image) {
image.setOrd(this.imageList.size());
imageList.add(image);
}
public void addImageString(String fileName) {
ProductImage productImage = ProductImage.builder()
.fileName(fileName)
.build();
addImage(productImage);
}
public void clearList() {
this.imageList.clear();
}
public void setSeller(User seller) {
this.seller = seller;
}
}
ProductRepository.java
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByPnameContainingIgnoreCase(String query);
}
ProductRepositoryTest.java
@Test
@Transactional
public void testFindByPnameContainingIgnoreCase(){
String searchQuery = "product";
List<Product> result = productRepository.findByPnameContainingIgnoreCase(searchQuery);
log.info(result.toString());
}
Queries
Hibernate:
select
p1_0.pno,
p1_0.category_num,
p1_0.date,
p1_0.del_flag,
p1_0.pdesc,
p1_0.pname,
p1_0.price,
p1_0.seller_user_id,
p1_0.view_count
from
tbl_product p1_0
where
upper(p1_0.pname) like upper(?) escape '\'
Hibernate:
select
u1_0.user_id,
u1_0.created_at,
u1_0.email,
u1_0.nickname,
u1_0.profile_image,
u1_0.pw,
u1_0.social,
u1_0.updated_at,
u1_0.user_user_name
from
tbl_user u1_0
where
u1_0.user_id=?
Hibernate:
select
rl1_0.user_user_id,
rl1_0.role_list
from
user_role_list rl1_0
where
rl1_0.user_user_id=?
Here’s the problem. The query below is repeated 1000 times.
Hibernate:
select
il1_0.product_pno,
il1_0.file_name,
il1_0.ord
from
product_image_list il1_0
where
il1_0.product_pno=?
I tried changing the fetchType of the entity or setting the batchsize but it didn’t work.