Spring4+Hibernate4+SpringMVC整合配置

这里是Spring4.3.9+Hibernate4.0.2的整合配置

配置web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>TestSpringSpringMVCHibernatedisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
      
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:applicationContext.xmlparam-value>  
    context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>  

      
    <servlet>  
        <servlet-name>dispatcherServletservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
          
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath:springmvc.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
    servlet>  
    <servlet-mapping>  
        <servlet-name>dispatcherServletservlet-name>  
        <url-pattern>*.dourl-pattern>  
    servlet-mapping>  

      
    <filter>  
        <filter-name>characterEncodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      
    <filter>  
        <filter-name>hiddenHttpMethodFilterfilter-name>  
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>  
    filter>  
    <filter-mapping>  
        <filter-name>hiddenHttpMethodFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  
  
web-app>

classpath:applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.1.xsd 
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

     <context:component-scan base-package="com.csq.myproject.*" />  
      
 <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName"
            value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/school">
        property>
        <property name="username" value="root">property>
        <property name="password" value="">property>
    bean>

      
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
          
        <property name="dataSource" ref="dataSource">property>  
          
        <property name="namingStrategy">  
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy">bean>  
        property>
          
         <property name="configLocation" value="classpath:hibernate.cfg.xml">property>
         
        <property name="packagesToScan" value="com.csq.myproject.entity">property> 
    bean>  


    
   <bean id="persistenceExceptionTranslationPostProcessor" 
       class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
  
     <bean id="transactionManager"   
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />  
 bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
tx:attributes>
tx:advice>
<aop:config expose-proxy="true">

<aop:pointcut id="txPointcut" expression="execution(* com.csq.myproject.service..*.*(..))" />

<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
aop:config>

    <bean id="userDao" class="com.csq.myproject.dao.impl.UserDaoImpl">
    <property name="sessionFactory" ref="sessionFactory">property> 
    bean>
    <bean id="managerDao" class="com.csq.myproject.dao.impl.ManagerDaoImpl">
    <property name="sessionFactory" ref="sessionFactory">property> 
    bean>

beans>

hibernate.cfg.xml




<hibernate-configuration>
    <session-factory>

        
        <property name="show_sql">trueproperty>

        
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>
        
        <property name="hibernate.hbm2ddl.auto">updateproperty>
        
       <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContextproperty>
    session-factory>
hibernate-configuration>

springmvc.xml


<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.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
<mvc:annotation-driven />
    <context:component-scan base-package="com.csq.myproject.web" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8">property>   
        <property name="maxUploadSize" value="10485760000">property>  
        <property name="maxInMemorySize" value="40960">property>  
   bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >    
  <property name="messageConverters">     
         <list>     
             <bean class = "org.springframework.http.converter.StringHttpMessageConverter">     
                <property name = "supportedMediaTypes">  
                      <list>  
                          <value>text/html;charset=UTF-8value>     
                     list>     
                property>     
             bean>     
         list>     
   property>    
bean>
beans>  

一些注解

service层

以UserServiceImpl为例子

@Service("userService") //配置service的bean
@Transactional      //事务
public class UserServiceImpl implements IUserService{
    @Autowired
    IUserDao userDao;//这里自动装配
    public void register(User user) {
        userDao.save(user);

    }
    public List queryAll() {
        return userDao.findAll();
    }
    public User findById(Integer id) {
        User user = (User)userDao.findById(User.class, id);
        return user;
    }

}

web层

以UserController为例子

@Controller
public class UserController{
    @Autowired//自动装配
    IUserService userService;
    //注册用户
    @RequestMapping(value="/register",method = RequestMethod.POST)
    public String register(Model model,@ModelAttribute("form")User user,HttpServletRequest request){
        userService.register(user);
        return "success";
    }
    //前端ajax请求返回json
    @RequestMapping(value="/showAllUser")
    public void register(HttpServletRequest request,HttpServletResponse response){
        List userList = userService.queryAll();
        JSONArray listJson = JSONArray.fromObject(userList);
        System.out.println(listJson.toString());
        try {
            response.getWriter().print(listJson);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(Java-web框架学习,hibernate,spring,springmvc)