I tried several solutions to my SQL query but it seems like I miss something.
I want to get a List<Product>
from a nativeQuery
.
And I have a relationship between my User
entity and Product
entity as One to Many.
Here is my both entites -> Product
@Entity
@Data
@Table(name = "product")
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreationTimestamp
@Column(updatable = false)
private Timestamp createdDate;
@UpdateTimestamp
private Timestamp lastModifiedDate;
private String imageURL;
private Long productCode;
@Size(min = 3,max = 100)
private String productName;
@Size(min = 5,max = 100)
private String details;
private BigDecimal price;
private ProductCategory productCategory;
}
User ->
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true,nullable = false)
private String phoneNumber;
@Size(min = 5, max = 25, message = "Username length should be between 5 and 25 characters")
@Column(unique = true, nullable = false)
private String userName;
@CreationTimestamp
@Column(updatable = false)
private Timestamp createdDate;
@UpdateTimestamp
private Timestamp lastModifiedDate;
@Column(unique = true, nullable = false)
@NotNull
private String email;
@Size(min = 5, message = "Minimum password length: 5 characters")
@NotNull
private String password;
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,orphanRemoval = true)
private List<Product> products;
@Transient
@OneToMany(fetch = FetchType.LAZY,mappedBy = "product",cascade = CascadeType.ALL,orphanRemoval = true)
private List<ProductInquiry> productInquiries;
private Role role;
}
Here in this query I need to return all products associated with the given user_id.
@Query(value = "SELECT new egecoskun121.com.crm.model.entity.Product(p.ID,p.CREATED_DATE,p.LAST_MODIFIED_DATE,p.IMAGEURL,p.PRODUCT_CODE,p.PRODUCT_NAME,p.DETAILS,p.PRICE,p.PRODUCT_CATEGORY) FROM PRODUCT AS p WHERE {SELECT PRODUCT_ID FROM USERS_PRODUCTS WHERE USER_ID=:id }",nativeQuery = true)
List<Product> findAllProductsById(@Param("id")Long id);