问题:
通过Junit单元测试Service可以将数据写入数据库;但部署却无法向数据库写入数据。
1、环境:
Spring 3.1.2
Hibernate 4.1.4
Jdk1.6
2、配置:
<!--[if !supportLists]-->1 <!--[endif]-->
<!--[if !supportLists]-->2 <!--[endif]-->
2.1、Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>springmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔此参数用于后面的Spring Context Loader -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--Dispathcer Servlet -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring MVC Servlet 拦截.do结尾的请求-->
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Filter 定义 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--openSessionInView-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.2 applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!--扫描并自动装配 -->
<context:annotation-config />
<context:component-scan base-package="com.sp" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:application.properties</value>
</property>
</bean>
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- Connection Info -->
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- Connection Pooling Info -->
<property name="maxActive" value="${dbcp.maxActive}" />
<property name="maxIdle" value="${dbcp.maxIdle}" />
<property name="defaultAutoCommit" value="false" />
<!-- 连接Idle一个小时后超时 -->
<property name="timeBetweenEvictionRunsMillis" value="3600000" />
<property name="minEvictableIdleTimeMillis" value="3600000" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.sp.dao</value>
<value>com.sp.entity.dict</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" abstract="false" lazy-init="default" autowire="default">
<property name="sessionFactory"><ref bean="sessionFactory" /></property>
</bean>
<!-- 事务管理配置 -->
<!--<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" read-only="false" propagation="REQUIRED" />
<tx:method name="get*" read-only="false" propagation="REQUIRED" />
<tx:method name="add*" read-only="false" propagation="REQUIRED" />
<tx:method name="update*" read-only="false" propagation="REQUIRED" />
<tx:method name="delete*" read-only="false" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor pointcut="execution(* com.sp.service.*.*(..))" advice-ref="txAdvice"/>
</aop:config>
</beans>
2.3 spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 启动注解驱动的SpringMVC功能,注册请求URL和注解POJO类方法的映射 -->
<mvc:annotation-driven />
<!-- 自动扫描且只扫描@Controller -->
<context:component-scan base-package="com.sp.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:component-scan base-package="com.sp.dao.impl"></context:component-scan>
<context:component-scan base-package="com.sp.service.impl"></context:component-scan>
<mvc:default-servlet-handler />
<!-- 对模型视图名称的解析,在请求时模型视图名称添加后缀。定义JSP -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
2.4 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings-->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
-->
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>-->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup-->
<property name="hbm2ddl.auto">update</property>
<property name="javax.persistence.validation.mode">none</property>
</session-factory>
</hibernate-configuration>
3 代码:
<!--[if !supportLists]-->1 <!--[endif]-->
<!--[if !supportLists]-->2 <!--[endif]-->
<!--[if !supportLists]-->3 <!--[endif]-->
3.1 Service层:
@Component("userService")
publicclass UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Autowired
private FormValidator validator;
@Override
public String userLogin(UserModel user) {
String password = userDao.userLogin(user);
if(password.equals(user.getPassword())){
return"sucess";
}else{
return"false";
}
}
@Override
public List<ProjectType> getAllProjectTypes(){
List<ProjectType> projectType = userDao.getAllProjectTypes();
return projectType;
}
//添加《项目类型》
@Override
public String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){
validator.validate(projectType, result);
if(result.hasErrors()){
return"newProjectType";
}
userDao.save(projectType);
//status.setComplete();
return"redirect:showProjectTypes.do";
}
//添加《项目类型》
@Override
public String addProjectType(ProjectType projectType) {
userDao.save(projectType);
return"redirect:showProjectTypes.do";
}
}
3.2 Control层
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private FormValidator validator;
@RequestMapping(value = "/login",method=RequestMethod.POST)
protected String handle(UserModel user,BindingResult result, Model model){
String flag = userService.userLogin(user);
System.out.println("flag:" + flag);
if ("sucess".equals(flag)){
return "sucess";
}
return "test1";
}
@RequestMapping(value = "/showProjectTypes")
protected ModelAndView getAllProjectTypes(){
ModelAndView mav = new ModelAndView("showProjectTypes");
List<ProjectType> projectTypes = userService.getAllProjectTypes();
mav.addObject("SEARCH_PROJECTTYPE_RESULTS_KEY", projectTypes);
return mav;
}
@RequestMapping(value = "/addProjectType",method=RequestMethod.GET)
protected ModelAndView newProjectTypeForm(){
ModelAndView mav = new ModelAndView("newProjectType");
ProjectType projectType = new ProjectType();
mav.getModelMap().put("newProjectType", projectType);
return mav;
}
@RequestMapping(value = "/saveProjectType",method=RequestMethod.POST)
protected String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){
//return userService.addProjectType(projectType, result, status);
return userService.addProjectType(projectType);
}
}
3.3 DAO@Component("userDao")
public class UserDaoImpl implements UserDao{
@Autowired
private SessionFactory sessionFactory;
public ProjectType getById(int id)
{
return (ProjectType) sessionFactory.getCurrentSession().get(ProjectType.class, id);
}
@Override
public String userLogin(UserModel user) {
return "123456";
}
//获取数据
@Override
@SuppressWarnings("unchecked")
public List<ProjectType> getAllProjectTypes() {
Criteria ceriteria = sessionFactory.getCurrentSession().createCriteria(ProjectType.class);
return ceriteria.list();
}
//新增数据;
@Override
// @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public int save(ProjectType projectType) {
System.out.println("save:---");
System.out.println(projectType.getIndex());
System.out.println(projectType.getProjectType());
System.out.println(projectType.getProjectTypeAbbr());
return (Integer) sessionFactory.getCurrentSession().save(projectType);
}
}