Unable to fetch Orders(which are not deleted) for logged in user - spring-boot

I am trying to fetch orders for logged in User which I was able to do. But now I have to orders for logged in User which are not marked as deleted as well. I am facing issue to fetch these records using spring-data-jpa. Same scenario I want to implement on User End.I am getting below exception -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-09-02 05:31:03.699 ERROR 220 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adminController': Unsatisfied dependency expressed through field 'journeyFoodServiceImpl'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'journeyFoodServiceImpl' defined in file [C:\Users\TiaaUser\Desktop\AWS\journeyfood\target\classes\org\brahmakumaris\journeyfood\service\JourneyFoodServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'journeyFoodOrderRepository' defined in org.brahmakumaris.journeyfood.repository.JourneyFoodOrderRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Using named parameters for method public abstract java.util.List org.brahmakumaris.journeyfood.repository.JourneyFoodOrderRepository.findOrderByUserIdAndNotDisabled(long,boolean) but parameter 'Optional[userId]' not found in annotated query 'SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,
j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from JourneyFoodOrder j INNER JOIN users u on u.userId=?1 WHERE j.isRemoved=:isRemoved'!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
Caused by: java.lang.IllegalStateException: Using named parameters for method public abstract java.util.List org.brahmakumaris.journeyfood.repository.JourneyFoodOrderRepository.findOrderByUserIdAndNotDisabled(long,boolean) but parameter 'Optional[userId]' not found in annotated query 'SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,
j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from JourneyFoodOrder j INNER JOIN users u on u.userId=?1 WHERE j.isRemoved=:isRemoved'!
at org.springframework.data.jpa.repository.query.JpaQueryMethod.assertParameterNamesInAnnotatedQuery(JpaQueryMethod.java:172)
at org.springframework.data.jpa.repository.query.JpaQueryMethod.<init>(JpaQueryMethod.java:139)
at org.springframework.data.jpa.repository.query.DefaultJpaQueryMethodFactory.build(DefaultJpaQueryMethodFactory.java:44)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:81)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:100)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,
j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from org.brahmakumaris.journeyfood.entity.JourneyFoodOrder j INNER JOIN users u on u.userId=:userId WHERE j.isRemoved=:isRemoved]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
JourneyFoodOrder.java Here isRemoved is getting used for marking orders as deleted.
#Entity
public class JourneyFoodOrder{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
private int headCount;
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dateOfOrderPlaced;
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dateOfDeparture;
#DateTimeFormat(pattern = "dd/MM/yyyy h:mm a")
private Date mealRetrievalTime;
#ManyToOne
private UserEntity user;
private int thepla;
private int puri;
private int roti;
private int achar;
private int jam;
private int bread;
private int others;
private boolean isRemoved;
//Getter setter and constructors
}
UserEntity.java Here isDisabled is used for marking User as disabled and enabled field for enabling(User verification via email).
#Entity
#Table(name="users")
public class UserEntity {
#Id
#Column(unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long userId;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "userId"), inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "roleId"))
private Set<Role> roles;
#Column(nullable = false, length = 100)
private String nameOfCenter;
#Column(nullable = false, length = 100)
private String nameOfGuide;
#Column(nullable = false, length = 18)
private String contactNoOfGuide;
#Column(nullable = false, unique = true, length = 70)
private String email;
#Column(nullable = false, length = 70)
private String zone;
#Column(nullable = false, length = 70)
private String subZone;
#Column(length = 10)
private Integer pincode;
private Date dateCreated;
private boolean isDisabled;
#Column(nullable = false, length = 150)
private String password;
#Column(nullable = false)
#Type(type = "org.hibernate.type.NumericBooleanType")
private boolean enabled;//whether account is verified using email or not
#OneToMany(mappedBy = "user")
#Fetch(FetchMode.JOIN)
private List<JourneyFoodOrder> order;
//Getters, setters and constructor
}
JourneyFoodOrderRepository.java
#Repository
public interface JourneyFoodOrderRepository extends JpaRepository<JourneyFoodOrder, Long>{
#Override
void delete(JourneyFoodOrder order);
#Modifying
#Query("update JourneyFoodOrder j set j.isRemoved =true where j.orderId =:id")
void updateIsRemoved(#Param("orderId")Long orderId);
List<JourneyFoodOrder> findByIsRemoved(boolean isRemoved);
#Modifying
#Query("SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,\r\n"
+ "j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from JourneyFoodOrder j INNER JOIN users u on u.userId=:userId WHERE j.isRemoved=:isRemoved")
List<JourneyFoodOrder> findOrderByUserIdAndNotDisabled(#Param("userId") long userId, #Param("isRemoved") boolean isRemoved);
}
Please help me out in resolving this issue.

In your for findOrderByUserIdAndNotDisabled method query, you have set method parameter as this j.isRemoved=:isRemoved. It should be change to j.isRemoved= ?2.
Here is the corrected Query
#Query("SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,"
+ "j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from JourneyFoodOrder j INNER JOIN users u on u.userId=?1 WHERE j.isRemoved= ?2")

I was using wrong Entity name causing this issue -
#Query("SELECT j.orderId,j.headCount,j.dateOfDeparture,j.dateOfOrderPlaced,j.mealRetrievalTime,j.achar,\r\n"
+ "j.bread,j.jam,j.puri,j.thepla,j.roti,j.others from JourneyFoodOrder j INNER JOIN UserEntity u on u.userId=:userId WHERE j.isRemoved=:isRemoved")
List<JourneyFoodOrder> findOrderByUserIdAndNotDisabled(#Param("userId") long userId, #Param("isRemoved") boolean isRemoved);
editing users to UserEntity did resolved my issue.

Related

not able to fetch data from the db when

I am getting an error when trying to fetch data from the database (the data exists in the db). I am able to perform the action when there is no data in the db.
This is my entities:
#Table(name = "tbl_task")
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
private String title;
private String description;
private Status status;
#ManyToOne
#JoinColumn(name = "user_id")
private User assignee;
#OneToMany(mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> comments;
and:
#Entity
#Table(name = "tbl_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
#Column(unique = true)
private String email;
private Active active;
private String password;
#OneToMany(mappedBy = "assignee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Task> tasks;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> comments;
the error is:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw
exception [Request processing failed; nested exception is
org.springframework.http.converter.HttpMessageNotWritableException: Could not write
JSON: Infinite recursion (StackOverflowError); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion
(StackOverflowError) (through reference chain:
com.tasksmanagement.entity.Task["assignee"]-
>com.tasksmanagement.entity.User["tasks"]-
>org.hibernate.collection.internal.PersistentBag[0]
This is the method:
public List<TaskResponse> getAllTasks() {
List<Task> tasks = taskRepository.findAll();
return
tasks.stream().map(this::mapToTaskResponse).collect(Collectors.toList());
}
Any idea how to solve this?
Thanks
I added #JsonManagedReference in the User class (List tasks field)
and added #JsonBackReference in the Task class (User asignee field) and it solved the issue

ERROR: syntax error at or near "." - JPA Pageable

repository:
#Repository
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {
#Query(value = "SELECT p.postComments FROM Post p WHERE p.webId = ?1")
Page<PostComment> findCommentsByWebId(String webid, Pageable pageable);
}
Post entity:
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "web_id")
private String webId;
#Column(nullable = false, name = "title")
private String title;
#Column(nullable = false, name = "description")
private String description;
#Column(nullable = false, name = "mature")
private boolean mature;
#OneToOne(mappedBy = "post")
private Cover cover;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#OneToMany(mappedBy = "post")
private List<PostView> postViews;
#ManyToMany
#JoinTable(name = "post_tag",
joinColumns = #JoinColumn(name = "post_id"),
inverseJoinColumns = #JoinColumn(name = "tag_id"))
private List<Tag> tags;
#OneToMany(mappedBy = "post")
private List<PostDownvote> postDownvotes;
#OneToMany(mappedBy = "post")
private List<PostUpvote> postUpvotes;
#OneToMany(mappedBy = "post")
private List<PostComment> postComments;
#Column(name = "created_at")
private Timestamp createdAt;
#Column(name = "updated_at")
private Timestamp updatedAt;
}
The problem: When returning plain List<PostComment> from the query method everything works fine. But if I change it to Page<PostComment> (I need total elements count), I get the following error:
2022-08-03 22:29:41.399 ERROR 9192 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: syntax error at or near "."
Position: 14
Hibernate: select tags0_.post_id as post_id1_6_0_, tags0_.tag_id as tag_id2_6_0_, tag1_.id as id1_10_1_, tag1_.name as name2_10_1_ from post_tag tags0_ inner join tag tag1_ on tags0_.tag_id=tag1_.id where tags0_.post_id=?
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
It is very difficult to debug this. Does anyone have any clue on what is wrong?
I need BOTH paging and total amount of elements.
Basically you are not able to fetch the part of the inner collection. But you could reach it from the another side of the bi-directional relationship
#Repository
public interface PostCommentRepository extends PagingAndSortingRepository<PostComment, Long> {
#Query(value = "SELECT pc FROM PostComment pc WHERE pc.post.webId = ?1")
Page<PostComment> findCommentsByWebId(String webid, Pageable pageable);
// or better using Spring Data naming conventions just
Page<PostComment> findAllByPostWebId(String webid, Pageable pageable);
}
If you only need a total count you should avoid querying list of entities which could be very memory intensive.
So in your PostCommentRepository try the following:
long countAllByPost_WebId(String webId);

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException

This is my orderservice implementation for creating and saving orders here with the customerid I'm getting customer and customer has a cart and in the cart product list is there and for that product list, I should create an order.
public Order save(int custid) {
Optional<Customer> cust = customerRepo.findById(custid);//here customer is there and inside customer cart is there inside cart medicine list is there.
Cart ct= cust.get().getCart();//getting cart from customer
if(ct.getMedicineList().size()!=0) {//create order only if the medicine list is not empty. there are 8 fields **orderDate,dispatchDate,status,medicineList,totalCost,customer and orderId(GeneratedValue)** I can't set the orderId cuz it is auto generated.
LocalDate todaysDate = LocalDate.now();
LocalDate dispatchdate = todaysDate.plusDays(3);
List<Medicine> orderList= new ArrayList<Medicine>();
List<Medicine> cartList= new ArrayList<Medicine>();
cartList=ct.getMedicineList();
orderList.addAll(cartList);
Order ord = new Order();
ord.setCustomer(cust.get());
ord.setMedicineList(orderList);
ord.setDispatchDate(dispatchdate);
ord.setOrderDate(todaysDate);
ord.setStatus("Placed");
ord.setTotalCost((float)ct.getTotalAmount());
logger.info("Add order to the database");
return orderRepository.save(ord);
}
return null;
}
this is my order controller
#PostMapping("/order/{custid}")
public ResponseEntity<Order> addOrder(#Valid #PathVariable("custid") int custid) {
logger.info("Add order in database");
return new ResponseEntity<>(orderService.save(custid), HttpStatus.OK);
}
this is my medicine Entity
#Data
#RequiredArgsConstructor
#ToString
#Table(name = "medicine")
#Entity
public class Medicine {
#Id
#Column(name = "medicine_id", nullable = false)
#NonNull
#GeneratedValue
private int medicineId;
#NonNull
#Size(min = 3, message = "Minimum charecters in medicine name should be 3.")
#NotEmpty
#Column(unique = true, name = "medicine_name", nullable = false)
private String medicineName;
#NonNull
#Column(name = "medicine_cost", nullable = false)
private float medicineCost;
#NonNull
#Column(name = "mfd", nullable = false)
private LocalDate mfd;
#NonNull
#Column(name = "expiry_date", nullable = false)
private LocalDate expiryDate;
#NonNull
#Column(name = "medicine_quantity", nullable = false)
private int medicineQuantity = 1;
#NonNull
private String medicineCategory;
#NonNull
private String medicineDescription;
#JsonIgnore
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "medicineList",fetch = FetchType.EAGER)
private List<Order> orderList;
}
this is my order Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Order {
#Id
#Column(name = "orderId")
#GeneratedValue
private int orderId;
#NonNull
private LocalDate orderDate;
#ManyToMany(targetEntity = Medicine.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "ord_med", joinColumns = { #JoinColumn(name = "ord_id") }, inverseJoinColumns = {
#JoinColumn(name = "med_id") })
private List<Medicine> medicineList = new ArrayList<>();
#NonNull
private LocalDate dispatchDate;
#NotEmpty
private float totalCost;
#NonNull
private String status;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="c_ord_fk",referencedColumnName = "customerId")
#NonNull
private Customer customer;
}
here when i try to create order for the list inside cart it gives me [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction]
i'm not sure but i think its because of the id but it is autogenerated. Idk how to create an order object for the list of products or is this the correct way to do it.
Actually I found the answer, all I have to do is when you use ManyToMany mapping the cascade type must be cascade = {CascadeType.MERGE,CascadeType.REFRESH} instead of {cascade = CascadeType.ALL} and it works fine. reference JPA: detached entity passed to persist: nested exception is org.hibernate.PersistentObjectException

Spring JPA. How to get only a list of IDs using #Query

I am trying to write this to fetch List and i have to pass the list of Ids as parameter :
#Query(value = "SELECT OutbreakDiagnosticTests FROM OutbreakDiagnosticTests WHERE OutbreakDiagnosticTests.outbreaks in (:outbreakIds) ")
List<OutbreakDiagnosticTests> getDiagnosticTestsByOutbreaks(#Param("outbreakIds") List<Long> outbreakIds);
My Entity is this that i am using to query is this :
#Entity
#EntityListeners(OutbreakDiagnosticTestManagerImpl.class)
#Table(name = "outbreak_diagnostic_tests")
public class OutbreakDiagnosticTests extends AbstractTemporalWorkingData implements Serializable{
/**
*
*/
private static final long serialVersionUID = 636298998880960358L;
#Id
#Column(nullable = false, name = "obdt_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long obdtId;
#Column(nullable = false, name = "nature", length = 255)
private String nature;
#Column(nullable = true, name = "diagnostic_test_req", length = 255)
private String diagnosticTestReq;
#OneToMany(mappedBy = "outbreakDiagnosticTests", cascade = CascadeType.ALL, orphanRemoval = true)
#Filter(name = "workingData")
private Set<TestsResults> testsResults;
#ManyToOne
#JoinColumn(name = "outbreak_id", nullable = false)
private Outbreaks outbreaks;
#ManyToOne
#JoinColumn(name = "diag_test_id", nullable = true)
private DiagnosticTests diagTests;
#ManyToOne
#JoinColumn(name = "lab_id", nullable = true)
private Laboratories lab;
#Column(nullable = false, name = "is_field")
private Boolean isField = false;
But i am getting this exception after running :
Error creating bean with name 'labTestSummariesDaoImpl': Unsatisfied dependency expressed through field 'obDiagTestRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'outbreakDiagnosticTestRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.wahisplus.wcommon.repository.outbreak.OutbreakDiagnosticTestRepository.getDiagnosticTestsByOutbreaks(java.util.List)!
Can some one help me to fetch the List using the above method or can tell me what i am doing wrong in this.I dnt want to do using native i.e (nativeQuery = true) using this.
Use alias like OutbreakDiagnosticTests o and for select id, use o.outbreaks.id and make sure you autowired properly repository
#Query(value = "SELECT o FROM OutbreakDiagnosticTests o WHERE o.outbreaks.id IN (:outbreakIds) ")
List<OutbreakDiagnosticTests> getDiagnosticTestsByOutbreaks(#Param("outbreakIds") List<Long> outbreakIds);
Since you are already using Spring Data JPA, a method is provided OOTB:
List findAllById(Iterable ids);
This method takes in a List of non-null ids and returns you back the records against those Ids. Since you are not using DTO Concept and fetching al columns for a bundh of ids, why not use this method to work with.

Can't create entity object with map with custom object

Spring boot 2.5
I has entity Cart. One cart has many entities Product. In one cart has many products. So I try with #JoinColumn but I get error:
#Entity
public class Cart {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToMany(mappedBy = "cart", fetch = FetchType.EAGER,
cascade = CascadeType.ALL)
private Map<Product, Integer> products;
}
import javax.persistence.*;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "cart_id", nullable = false)
private Cart cart;
}
But when I try to run application I get error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cartRepository' defined in com.myproject.eshop_orders.repo.CartRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.myproject.eshop_orders.api.model.Cart.products[java.lang.Integer]
If you want a map you need to use #MapKeyJoinColumn. Something like this
#Entity
public class Cart {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#MapKeyJoinColumn(name="PRODUCT_ID")
#OneToMany(mappedBy = "cart", fetch = FetchType.EAGER,
cascade = CascadeType.ALL)
private Map<Product, Integer> products;
}
One cart has many different products.
Also I need to store quantity of products in cart (value in map)
Here my solution:
#Entity
public class Cart {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ElementCollection
#CollectionTable(name = "cart_products", joinColumns = #JoinColumn(name = "cart_id"))
#MapKeyJoinColumn(name = "product_id")
#Column(name = "product_qantity")
private Map<Product, Integer> products;
}
import javax.persistence.*;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "cart_id", nullable = false)
private Cart cart;
}
Is this a correct solution?

Resources