2 vipsh2011 vipsh2011 于 2013.11.06 13:55 提问

请教:Spring + Hibernate 无法将数据写入数据库?

Spring + Hibernate 无法将数据写入数据

请教: 通过Junit单元测试Service可以将数据写入数据库;但部署访问却无法向数据库写入数据。

1 环境:
Spring 3.1.2
Hibernate 4.1.4
Jdk1.6
2 配置:
2.1 Web.xml
<!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring Context Loader -->

contextConfigLocation
classpath*:/applicationContext.xml

<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-->

openSessionInView
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter

sessionFactoryBeanName
sessionFactory

<filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2.2 applicationContext.xml
<!--扫描并自动装配 -->



classpath:application.properties

<!-- 数据源配置 -->

<!-- Connection Info -->



    <!-- 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>

2.3 spring-mvc.xml

<!-- 启动注解驱动的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" />

2.4 hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
root
password

<!-- 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>

3 代码:
3.1 Service层:
@Component("userService")
public class 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);
}

}

1个回答

springmvc_springdata
springmvc_springdata   2014.08.09 10:30

spring框架中多数据源创建加载并且实现动态切换的配置实例代码 http://www.zuidaima.com/share/1774074130205696.htm

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!