进击的小小学生 2013-11-06 13:44 采纳率: 0%
浏览 330
已采纳

Spring + Hibernate4 无法将数据写入数据【请教】

 

 问题:

通过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);

         }

 

}

  • 写回答

3条回答 默认 最新

  • jinnianshilongnian 2013-11-06 14:36
    关注

    你测试用例怎么写的 估计是配置了
    @TransactionConfiguration(defaultRollback = true) 默认回滚

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀