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

整体目录结构:


其中包下全部是采用mybatis自动生成工具生成。

mybatis自动生成文件

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

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

<generatorConfiguration>

 

<!--加载属性文件 -->

<properties resource="db.properties" />

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

    }

    

}

 






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值