Spring+SpringMVC+Mybatis大整合(SpringMVC採用REST風格、mybatis採用Mapper代理)

總體目錄結構:html


其中包下所有是採用mybatis自動生成工具生成。java

mybatis自動生成文件web

<?xml version="1.0" encoding="UTF-8" ?>spring

<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >sql

<generatorConfiguration>數據庫

 

<!--加載屬性文件 -->apache

<properties resource="db.properties" />spring-mvc

<context id="context1">緩存

<commentGenerator>服務器

<property name="suppressDate" value="true" />

<!-- 是否去除自動生成的註釋 true:是 : false:否 -->

<property name="suppressAllComments" value="true" />

</commentGenerator>

 

<!-- 數據庫鏈接URL,用戶名,密碼 -->

<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}" />

<!--生成模型的包名和位置 -->

<javaModelGenerator targetPackage="mybatisGenerator.rawMode" targetProject="orderManage2/src" />

<!--映射文件的包名和位置 -->

<sqlMapGenerator targetPackage="mybatisGenerator.rawMapper" targetProject="orderManage2/src" />

<!--DAO的包名和位置 -->

<javaClientGenerator targetPackage="mybatisGenerator.rawMapper" targetProject="orderManage2/src" type="XMLMAPPER" />

<!--要生成哪些表 -->

<table schema="" tableName="user" domainObjectName="RawUser" enableCountByExample="false" enableUpdateByExample="false"

enableDeleteByExample="false" enableSelectByExample="false" />

<table schema="" tableName="goods" domainObjectName="RawGoods" enableCountByExample="false" enableUpdateByExample="false"

enableDeleteByExample="false" enableSelectByExample="false" />

<table schema="" tableName="orders" domainObjectName="RawOrders" enableCountByExample="false" enableUpdateByExample="false"

enableDeleteByExample="false" enableSelectByExample="false" />

<table schema="" tableName="address" domainObjectName="RawAddress" enableCountByExample="false" enableUpdateByExample="false"

enableDeleteByExample="false" enableSelectByExample="false" />

</context>

</generatorConfiguration>



爲了方便之後數據庫的修改以及需求修改等因素,我以爲應該把全部的自動生成的代碼放進一個包中,而後在外邊繼承它裏邊的東西。這樣方便之後從新自動生成,又不會影響咱們本身手動編寫的部分。

config包下所有爲配置文件。

SqlMapConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

 

<!-- 加載屬性文件 -->

<!-- <properties resource="classpath:db.properties">

properties中還能夠配置一些屬性名和屬性值

<property name="jdbc.driver" value=""/>

</properties> -->

<!-- 全局配置參數,須要時再設置 -->

<!-- 延遲加載的配置,懶加載 -->

<settings>

 

<!-- 打開延遲加載的開關  -->

<setting name="lazyLoadingEnabled" value="true"/>

<!-- 將積極加載變爲消極加載     按需加載 --> 

<setting name="aggressiveLazyLoading" value="false"/>

<!-- 開啓二級緩存   默認是開啓的 -->

<setting name="cacheEnabled" value="true"/>

</settings>

<!-- 別名定義 -->

<typeAliases>

<!-- 針對單個別名定義 type:類型的路徑 alias:別名 -->

<!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->

<!-- 批量別名定義 指定包名,mybatis自動掃描包中的pojo類,自動定義別名,別名就是類名(首字母大寫或小寫均可以) -->

<package name="mode" />

</typeAliases>

<!-- 和spring整合後 environments配置將廢除 -->

<!-- <environments default="development">

<environment id="development">

使用jdbc事務管理,事務控制由mybatis

<transactionManager type="JDBC" />

數據庫鏈接池,由mybatis管理

<dataSource type="POOLED">

<property name="driver" value="${jdbc.driver}" />

<property name="url" value="${jdbc.url}" />

<property name="username" value="${jdbc.username}" />

<property name="password" value="${jdbc.password}" />

</dataSource>

</environment>

</environments> -->

<!-- 經過mapper接口加載映射文件:須要遵循一些規範:須要將mapper接口名稱和mapper.xml映射文件保持一致,且在一個目錄中 放在一個目錄 ,且同名 前提是:使用的事mapper代理方式 -->

<!--  和spring整合後,用的是mapper掃描器,就不須要配置-->

<!-- <mappers>

<package name="ssm.mapper" />

</mappers> -->

</configuration>

-------------------------------------------applicationContext_dao.xml--------------------------------------------------------------

<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:context="http://www.springframework.org/schema/context"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 

http://www.springframework.org/schema/mvc 

http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 

http://www.springframework.org/schema/context 

http://www.springframework.org/schema/context/spring-context-3.2.xsd 

http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 

http://www.springframework.org/schema/tx 

http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

 

<!-- 加載配置文件 -->

<context:property-placeholder location="classpath:db.properties" />

 

<!-- 數據源,使用dbcp -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<property name="driverClassName" value="${jdbc.driver}" />

<property name="url" value="${jdbc.url}" />

<property name="username" value="${jdbc.username}" />

<property name="password" value="${jdbc.password}" />

<property name="maxActive" value="10" />

<property name="maxIdle" value="5" />

</bean>

 

 

<!-- sqlSessinFactory -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<!-- 數據庫鏈接池-->

<property name="dataSource" ref="dataSource" />

<!-- 加載mybatis的配置文件 -->

<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />

</bean>

<!--mapper批量自動掃描,從mapper包中掃描出mapper接口,自動生成代理對象,而且加入註冊到spring的bean中  -->

<!-- 須要遵循一些規範:須要將mapper接口名稱和mapper.xml映射文件保持一致,且在一個目錄中 放在一個目錄 ,且同名 前提是:使用的事mapper代理方式 -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<!--指定掃描的報名  -->

<!-- 自動掃描出來的mapper對應的名稱爲類名稱(首字母小寫)  若是掃描多個包,則用半角逗號隔開 -->

<property name="basePackage" value="mybatisGenerator.rawMapper,mapper"/>

<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

</bean>

 

</beans>

 -------------------------------------------------------------applicationContext_services.xml--------------------------------------------------------------------------------------------------

<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:context="http://www.springframework.org/schema/context"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 

http://www.springframework.org/schema/mvc 

http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 

http://www.springframework.org/schema/context 

http://www.springframework.org/schema/context/spring-context-3.2.xsd 

http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 

http://www.springframework.org/schema/tx 

http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

 

<bean id="orderService" class="service.impl.OrderServiceImpl"/>

<bean id="userService" class="service.impl.UserServiceImpl"/>

 

</beans>

 -------------------------------------------------------------------------------------------applicationContext_transaction.xml--------------------------------------------------------------------------------------------------------------------

<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:context="http://www.springframework.org/schema/context"

xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 

http://www.springframework.org/schema/mvc 

http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 

http://www.springframework.org/schema/context 

http://www.springframework.org/schema/context/spring-context-3.2.xsd 

http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 

http://www.springframework.org/schema/tx 

http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

 

<!--事物管理器:對於mybatis操做事物,spring採用jdbc事物控制類進行管理  -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<!--在beans裏邊配置的dataSource  -->

<property name="dataSource" ref="dataSource"></property>

</bean>

<!-- 通知 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="save*" propagation="REQUIRED"/>

<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>

</tx:attributes>

</tx:advice>

<!--aop  -->

<aop:config>

<aop:advisor advice-ref="txAdvice" pointcut="execution(* service.impl.*.*(..))"/>

</aop:config>

 

</beans>

 ----------------------------------------------------------------------springmvc.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.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">

<!-- 配置自動掃描的包 -->

<context:component-scan base-package="controller;mode;service" />

<!--配置視圖解析器 -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />

</bean>

 

<!-- 將在SpringMVC上下文中定義一個DefaultServletHttpRequestHandler, 他會對進入DispatcherServlet的請求 進行篩選,若是發現是沒通過映射的請求,就將請求交給WEB的應用服務器默認 的Servlet處理,若是不是靜態資源的請求,才由DispatcherServlet繼續處理 

通常WEB應用服務器的Servlet的名稱都是default -->

<mvc:default-servlet-handler />

<mvc:annotation-driven></mvc:annotation-driven>

 

<!-- 配置上傳文件MultipartResolver-->

<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

配置上傳文件的編碼方式

<property name="defaultEncoding" value="UTF-8"/>

配置上傳文件最大值

<property name="maxUploadSize" value="102400000"/>

</bean> -->

<!--  配置SpringMVC攔截器-->

<!-- <mvc:interceptors>

攔截全部的請求 

<bean class="interceptor.FirstInterceptor"/>

配置攔截器做用的路徑   和不做用的路徑 

<mvc:interceptor>

<mvc:mapping path="/abc"/>

<mvc:exclude-mapping path="/efg"/>

<bean class="interceptor.FirstInterceptor" />

</mvc:interceptor>

</mvc:interceptors> -->

 

</beans>

 ------------------------------------------------------------------------------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" 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>orderManage2</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>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  

  

  

  <!--配置SpringMVC的DispatcherServlet -->

<servlet>

<servlet-name>springDispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<!--配置DispatcherServlet的一個初始化參數:做用是,配置SpringMVC配置文件的位置和名稱 -->

<param-name>contextConfigLocation</param-name>

<param-value>classpath:spring/springmvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

 

<servlet-mapping>

<servlet-name>springDispatcherServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

 

 

 

<!-- 加載spring文件 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/classes/spring/applicationContext_*.xml</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 

 

 

<!-- 配置filter:把POST 請求轉化爲DELETE、PUT請求 -->

<filter>

<filter-name>HiddenHttpMethodFilter</filter-name>

<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

</filter>

 

<filter-mapping>

<filter-name>HiddenHttpMethodFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>



UserController.java

---------------------------------------------------------------------------------------------------------


 

package controller;

 

import java.util.List;

import java.util.Map;

 

import mapper.AddressMapper;

import mode.User;

import mode.UserVo;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

 

import service.inter.UserService;

 

@Controller

public class UserController {

    @Autowired

    private UserService userService;

    

    @Autowired

    private AddressMapper addressMapper;

    

    

    /**

     * 修改保存操做

     * 

     * @RequestMapping("/addUser")使用requestMapping來映射URL method對應的請求方式

     * @throws Exception 

     */

    @RequestMapping(value="/saveUser", method=RequestMethod.PUT)

    public String updateUser(User user) throws Exception{

        userService.updateUser(user);

        return "redirect:/getUsers";

    }

    

    

    /**

     * 修改操做

     * 

     * @RequestMapping("/addUser")使用requestMapping來映射URL method對應的請求方式

     * @PathVariable("id")路徑URL中的參數信息

     * @throws Exception 

     */

    @RequestMapping(value="/editUser/{id}", method=RequestMethod.GET)

    public ModelAndView editUser(@PathVariable("id") Integer id, Map<String, Object> map) throws Exception{

        

        ModelAndView view = new ModelAndView();

        view.setViewName("putUser");

        

        view.addObject("addressVoList", addressMapper.findAddressList(null));

        // 對應struts1裏邊的from表單對象

        view.addObject("user", userService.findUser(id));

        return view;

    }

    

    

    

    /**

     * 刪除操做

     * 

     * @RequestMapping("/addUser")使用requestMapping來映射URL method對應的請求方式

     * @PathVariable("id")進行接受參數

     * @throws Exception 

     */

    @RequestMapping(value="/deleteUser/{id}", method=RequestMethod.DELETE)

    public String deleteUser(@PathVariable("id") Integer id) throws Exception{

        userService.deleteUser(id);

        //刪除後進行顯示操做

        return "redirect:/getUsers";

    }

    

    /**

     * 保存操做

     * 

     * @RequestMapping("/addUser")使用requestMapping來映射URL method對應的請求方式

     * @throws Exception 

     */

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)

    public String saveUser(User user) throws Exception {

        userService.saveUser(user);

        // 保存完成後進入到顯示操做

        return "redirect:/getUsers";

    }

    

    

    /**

     * 進入到添加操做頁面

     * 

     * @RequestMapping("/addUser")使用requestMapping來映射URL method對應的請求方式

     * @throws Exception 

     */

    @RequestMapping(value = "/addUser", method = RequestMethod.GET)

    public ModelAndView addUser() throws Exception {

        ModelAndView view = new ModelAndView();

        view.setViewName("putUser");

        

        view.addObject("addressVoList", addressMapper.findAddressList(null));

        // 對應struts1裏邊的from表單對象

        view.addObject("user", new User());

        return view;

    }

    

    /**

     * 顯示操做

     * 

     * @RequestMapping("/getUsers")使用requestMapping來映射URL method對應的請求方式

     * @throws Exception 

     */

    @RequestMapping("/getUsers")

    public ModelAndView getUsers() throws Exception{

        ModelAndView view = new ModelAndView();

        view.setViewName("listUsers");

        

        List<UserVo> users = userService.findUserList(null);

        view.addObject("users", users);

        

        

        return view;

    }

    

}

相關文章
相關標籤/搜索