我是Spring MVC和HiberNate的新手,我的会话配置有问题。我是通过使用Hibernate来做到这一点的。我现在想做的是将在DAO中自动装配会话工厂。
这是应用程序上下文。xml -
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable @Controller annotation support -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/jsp" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_nutsaboutcandy"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>com.nutsaboutcandywebproject.model</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
这是完整的堆栈跟踪。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet appServlet
java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
这是刀的代码
package com.nutsaboutcandywebproject.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.nutsaboutcandywebproject.model.Category;
import com.nutsaboutcandywebproject.model.Inventory;
import com.nutsaboutcandywebproject.model.Product;
import com.nutsaboutcandywebproject.model.ProductTypes;
public class SQLProductsDataAccess implements IProductsDataAccess {
@Autowired
SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public Inventory getInventory()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Product";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
@SuppressWarnings("unchecked")
List<Product> productsList = (List<Product>) query.list();
Inventory inventory = new Inventory();
inventory.setProducts(productsList);
transaction.commit();
session.close();
return inventory;
}
public Product getProductById(Integer id) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query hqlQuery = session.createQuery("from Product WHERE id = :id");
hqlQuery.setParameter("id", id);
System.out.println("Query created...");
List<?> productList = hqlQuery.list();
Product product = (Product) productList.get(0);
transaction.commit();
session.close();
return product;
}
public List<Category> getCategoryName()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Category";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<Category> categoryList = query.list();
transaction.commit();
session.close();
return categoryList;
}
@Override
public Integer addStock(Integer id)
{
Product product = getProductById(id);
int quantity = product.getQuantityInStock() + 1000;
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", quantity);
query.setParameter("id", id);
query.executeUpdate();
transaction.commit();
session.close();
return quantity;
}
@Override
public List<ProductTypes> getTypeName() {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from ProductTypes";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<ProductTypes> typeList = query.list();
transaction.commit();
session.close();
return typeList;
}
@Override
public void updateProduct(Integer updatedQuantity, Integer productId) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", updatedQuantity);
query.setParameter("id", productId);
System.out.println("Query created...");
query.executeUpdate();
transaction.commit();
session.close();
}
@Override
public Integer deleteProduct(Integer productId)
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("delete Product where id = :id");
query.setParameter("id",productId);
int result = query.executeUpdate();
transaction.commit();
session.close();
return result;
}
}
购物车控制器
package com.nutsaboutcandywebproject.controller;
@SessionAttributes(value = {"customerSession","cartSession"})
@Controller
public class ShoppingCartController {
private ServiceFacade facade = new ServiceFacadeImpl();
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList = facade.getAllProducts();
private List<Category> categoryList = facade.getCategory();
private List<ProductTypes> typeList = facade.getType();
private List<Sizes> sizeList = facade.getAllSizes();
private List<ProductPriceMatrix> priceMatrixList = facade.getProductPriceMatrices();
private List<String> exceptionList = new ArrayList<String>();
@RequestMapping(value = "/cart", method = RequestMethod.POST)
public String doShop(Model model, @RequestParam("smallSize") String[] small,
@RequestParam("mediumSize") String[] medium ,@RequestParam("largeSize") String[] large)
{
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
List<ShoppingCart> cartList = new ArrayList<ShoppingCart>();
boolean isCartEmpty = true;
if(session.getAttribute("cartSession")!=null){
cartList = (List<ShoppingCart>) session.getAttribute("cartSession");
isCartEmpty = false;
}
for(int index=0; index<productsList.size();index++){
int numberOfSmall = 0;
int numberOfMedium = 0;
int numberOfLarge = 0;
Integer productId = productsList.get(index).getId();
Sizes size = priceMatrixList.get(index).getSize();
Product product = facade.getSingleProduct(productId);
try{
exceptionsNAC.numberCheck(small[index]);
exceptionsNAC.numberCheck(medium[index]);
exceptionsNAC.numberCheck(large[index]);
exceptionsNAC.checkValues(small[index]);
exceptionsNAC.checkValues(medium[index]);
exceptionsNAC.checkValues(large[index]);
numberOfSmall = Integer.parseInt(small[index]);
numberOfMedium = Integer.parseInt(medium[index]);
numberOfLarge = Integer.parseInt(large[index]);
}catch(ProductException e){
exceptionList.add(e.getMessage());
}
User user = (User) session.getAttribute(("customerSession"));
if(small[index] != null && numberOfSmall!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(50,numberOfSmall,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfSmall);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(medium[index] != null && numberOfMedium!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(100,numberOfMedium,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfMedium);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(large[index] != null && numberOfLarge!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(150,numberOfLarge,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfLarge);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
}
if(isCartEmpty){
session.setAttribute("cartSession", cartList);
}
model.addAttribute("cartSession", cartList);
model.addAttribute("productsList", productsList);
model.addAttribute("categoryList", categoryList);
model.addAttribute("typeList", typeList);
model.addAttribute("sizeList", sizeList);
model.addAttribute("priceMatrixList", priceMatrixList);
model.addAttribute("exception", exceptionList);
return "/ShoppingCart";
}
}
再添加几行这样的代码——以便启动bean和数据源
<bean id="shoppingCartController" class="point.it.to.implementation.class">
<property name="mySessionFactory" ref="mySessionFactory"/>
</bean>
您甚至可以尝试使用@Autowired注释,只需为其创建setter方法。
您的DAO和服务对象需要是Spring控制下的bean。通过像这样实例化它们:
private ServiceFacade facade = new ServiceFacadeImpl();
Spring永远无法注入依赖项并将所有内容连接起来,因此NPE
。将以下内容添加到XML文件中
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.service"/>
并确保您的 DAO 标记为 @Repository
或 @Component,并将您的服务标记为 @Service
或 @Component
。并将
立面
的实例化更改为
@Autowired
private ServiceFacade facade;
由于没有对DAO包进行扫描,因此几乎肯定必须在ServiceFacadeImpl
及其IProductsDataAccess
字段中执行同样的操作。
更新:除此之外,您正在访问尚未初始化的bean,例如。
private List<Product> productsList = facade.getAllProducts();
在那个时间点,即在对象实例化期间,Spring还没有完成创建您的DAO、HiberNate会话工厂等。您只能在Spring完成初始化和注入依赖项时访问这些bean并设置您的字段。为此,请将代码放在标记为@PostCon结构体
的初始化方法中:
@Controller
public class ShoppingCartController {
@Autowired
private ServiceFacade facade;;
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList;
private List<Category> categoryList;
private List<ProductTypes> typeList;
private List<Sizes> sizeList;
private List<ProductPriceMatrix> priceMatrixList;
private List<String> exceptionList = new ArrayList<String>();
@PostConstruct
public void someInitializationMethod() {
productsList = facade.getAllProducts();
categoryList = facade.getCategory();
typeList = facade.getType();
sizeList = facade.getAllSizes();
priceMatrixList = facade.getProductPriceMatrices();
}
....
组件扫描配置中缺少“dao”包:
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
此外,DAO类必须具有@Repostory注释才能将其用作自动装配的组件。
我有几个类注释为@Transactional 例如,我有第一类,这是Spring旋转变压器 类 我有一个控制器类,也标注了@Transactional 问题是每次我访问testDao.load(Test.class,1)hibernate时都会向数据库发出查询,而不是拉Test。控制器中的缓存中的类id=1。 为什么它不使用缓存?这两个调用在每个请求中发生,但似乎在不同的会话中。 如果我在控制器中
问题内容: 我刚刚有了Hibernate Session和Connection之间的关系。但是现在,我又遇到一个问题:hibernate会话工厂如何管理会话?在以下代码段中:DAO类的save()方法: 当我们调用时,它将创建一个新会话(通过ThreadLocal附加到当前线程),该会话也附加到JDBC连接。但是,正如您所看到的,我们不需要关闭该会话(会话。 close()),都没有连接。那么,H
问题内容: 除以下内容外,我们还有其他区别吗?另外请验证以下内容是否正确 每个应用程序一个对象,每个客户端一个对象。 是创建和管理。是为映射的类提供CRUD接口,并提供更多功能。 是线程安全的,而不是线程安全的 问题答案: 首先,询问这些接口之间的区别没有任何意义。好像在问汽车制造厂和汽车之间的区别。制造工厂是生产汽车的地方。同样,是一个将创建对象的实例。
我试图将Spring MVC与Hibernate(即HibernateTemplate)集成,但却被这个ClassCastException ie org所困扰。springframework。orm。hibernate4.LocalSessionFactoryBean无法转换为org。冬眠SessionFactory。我正在使用Hibernate-4(ie-org.springframework
另一种方法是使用Crieteria关联,但关联只能与和一起工作! 请在这里帮帮我。
我无法在创建模式下以Hibernate空间启动我的Spring启动(2.6.3)项目。它告诉我类型“几何不存在”。几何类型来自Hibernate空间库。 但是,我应用了所有必要的东西: > 添加Hibernate空间依赖项(我的版本5.6.3.Final) 使用组织.hibernate.空间.方言.postgis.Postgis方言 此外,该类已被弃用,文档对应于相同的版本,它仍然指示使用它,我不