Cart.java
@Entity
@Table(name = "cart")
public class Cart {
@Id
@GeneratedValue
@Column(name = "cart_id")
private int id;
@Column(name = "cart_status")
private int status;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "cart",fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<OrderDetails> orderDetails ;
@OneToMany(mappedBy = "cart", cascade = CascadeType.ALL)
private List<Transactions> transactions ;
}
CartController.java
@RequestMapping("/displaycart")
public String displayCart(Map<String, Object> map, Principal principal) {
String name = null;
if (principal != null) {
name = principal.getName();
}
User user = userService.findUserByName(name);
Cart isCartExisting = cartService.isCartExisting(user.getId());
List<OrderDetails> orderDetails=isCartExisting.getOrderDetails();
map.put("orderDetails", orderDetails);
for(OrderDetails o:orderDetails)
{
System.out.println(o.getProducts());
}
return "redirect:/productlist";
}
cartserviceimpl.java
@Service
public class CartServiceImpl implements CartService {
@Autowired
private CartDao cartDao;
@Autowired
private OrderDetailsService orderDetailsService;
@Override
@Transactional
public Integer saveCart(User user, int productid) {
Product product = new Product(productid);
Cart cart = new Cart();
cart.setUser(user);
cart.setStatus(0);
OrderDetails orderDetails1 = new OrderDetails();
orderDetails1.setUser(cart.getUser());
orderDetails1.setProducts(product);
orderDetails1.setCart(cart);
List<OrderDetails> listOfOrders = new ArrayList<OrderDetails>();
listOfOrders.add(orderDetails1);
cart.setOrderDetails(listOfOrders);
int result = cartDao.saveCart(cart);
System.out.println(result);
return result;
}
@Override
@Transactional
public int saveCart(User user, int cartid, int productid) {
Cart cart = cartDao.getCart(cartid);
//is order details existing with given product id?
OrderDetails isItemExisting = orderDetailsService.isItemExisting(productid);
if(isItemExisting!=null){
//add in existing
isItemExisting.setQuantity(isItemExisting.getQuantity()+1);
List<OrderDetails> listOfOrders = new ArrayList<OrderDetails>();
listOfOrders.add(isItemExisting);
cart.setOrderDetails(listOfOrders);
int result = cartDao.saveCart(cart);
System.out.println(result);
return result;
}else{
//new
Product product = new Product(productid,1);
OrderDetails orderDetails1 = new OrderDetails();
orderDetails1.setUser(cart.getUser());
orderDetails1.setProducts(product);
orderDetails1.setCart(cart);
List<OrderDetails> listOfOrders = new ArrayList<OrderDetails>();
listOfOrders.add(orderDetails1);
cart.setOrderDetails(listOfOrders);
int result = cartDao.saveCart(cart);
System.out.println(result);
return result;
}
}
@Override
@Transactional(readOnly = true)
public Cart isCartExisting(int userID) {
return cartDao.isCartExisting(userID);
}
}
orderdetails.java
@Entity
@Table(name = "order_details")
public class OrderDetails {
@Id
@GeneratedValue
@Column(name = "orderdetails_id")
private int id;
@Column(name = "product_quantity")
private int quantity;
@ManyToOne(optional = false)
@JoinColumn(name = "product_id")
private Product products;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
User user;
@ManyToOne(optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "cart_id")
Cart cart;
}
product.java
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue
@Column(name = "product_id")
private int id;
@Column(name = "product_name")
private String name;
@Column(name = "product_price")
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@OneToMany(mappedBy = "products", cascade = CascadeType.ALL)
private List<OrderDetails> orderDetails;
}
cartdaoimpl.java
public class CartDaoImpl implements CartDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public Integer saveCart(Cart cart) {
return (Integer) getSession().save(cart);
}
@Override
public Cart isCartExisting(int userID) {
Criteria c = getSession().createCriteria(Cart.class);
c.add(Restrictions.eq("user", new User(userID))).add(
Restrictions.eq("status", new Integer(0)));
return (Cart) c.uniqueResult();
}
private Session getSession() {
Session sess = getSessionFactory().getCurrentSession();
if (sess == null) {
sess = getSessionFactory().openSession();
}
return sess;
}
private SessionFactory getSessionFactory() {
return sessionFactory;
}
@Override
public Cart getCart(int id) {
Cart cart = (Cart) getSession().get(Cart.class, new Integer(id));
return cart;
}
}
我得到了这个受欢迎的
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.addtocart.dto.Cart.orderDetails, could not initialize proxy - no Session
type Exception report
message Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.addtocart.dto.Cart.orderDetails, could not initialize proxy - no Session
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.addtocart.dto.Cart.orderDetails, could not initialize proxy - no Session
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.addtocart.dto.Cart.orderDetails, could not initialize proxy - no Session
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294)
com.addtocart.controller.CartController.displayCart(CartController.java:57)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
,我在cart.java上经历了许多解决方案,例如fetch =FetchType.EAGER
和@lazy(false)
,但是无法解决这个问题,可以解释为什么我会得到即使我正在急切地使用{获取所有值{1}}。任何人都可以通过任何方式解决这个问题。
git hub link- https://github.com/emosrb/AddToCart