mybatis實戰教程三:mybatis和springmvc整合,mybatisspringmvc

來源:互聯網
上載者:User

mybatis實戰教程三:mybatis和springmvc整合,mybatisspringmvc
一、搭建maven環境,引入相關jar

參考demo

二、寫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>Archetype Created Web Application</display-name>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list>    <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>    <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>    <listener>        <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>    </listener>    <servlet>        <servlet-name>mvc-dispatcher</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>mvc-dispatcher</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

 

三、寫springmvc的xml檔案mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">    <context:component-scan base-package="com.yihaomen.mybatis" />    <mvc:annotation-driven />    <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />    <mvc:default-servlet-handler/>    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix">            <value>/WEB-INF/pages/</value>        </property>        <property name="suffix">            <value>.jsp</value>        </property>    </bean></beans>

 

四、寫spring的設定檔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:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:p="http://www.springframework.org/schema/p"       xsi:schemaLocation="            http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd            http://www.springframework.org/schema/jee            http://www.springframework.org/schema/jee/spring-jee-3.0.xsd            http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"       default-autowire="byName" default-lazy-init="false">    <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="location" value="classpath:jdbc.properties" />    </bean>    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" 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="initialSize" value="10" />        <property name="minIdle" value="10" />        <property name="maxActive" value="20" />        <!-- 配置擷取串連等待逾時的時間 -->        <property name="maxWait" value="60000" />        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑串連,單位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一個串連在池中最小生存的時間,單位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="SELECT 'x'" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 開啟PSCache,並且指定每個串連上PSCache的大小 -->        <property name="poolPreparedStatements" value="true" />        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />        <!-- 配置監控統計攔截的filters,去掉後監控介面sql無法統計 -->        <property name="filters" value="stat" />    </bean>    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <bean id="demoSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!--dataSource屬性指定要用到的串連池-->        <property name="dataSource" ref="dataSource"/>        <!--configLocation屬性指定mybatis的核心設定檔-->        <property name="configLocation" value="classpath:mybatis-config.xml"/>        <property name="mapperLocations" value="classpath:com/yihaomen/mybatis/model/*.xml"/>    </bean></beans>
五、mybatis-config.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>    <settings>        <!--這個配置使全域的映射器啟用或禁用緩衝-->        <setting name="cacheEnabled" value="true"/>        <!--           允許jdbc支援產生的鍵。需要適合的驅動。如果設定為true,           則這個設定強制產生的鍵被使用,儘管一些驅動拒絕相容但           仍然有效        -->        <setting name="useGeneratedKeys" value="true"/>        <!--配置預設的執行器。SIMPLE執行器沒有什麼特別之初。        REUSE執行器重用預先處理語句。BATCH執行器重用語句和批次更新-->        <setting name="defaultExecutorType" value="REUSE"/>        <!--設定逾時時間,它決定驅動等待一個資料庫相應時間-->        <setting name="defaultStatementTimeout" value="25000"/>    </settings>    <!--配置別名-->    <typeAliases>        <typeAlias alias="Student" type="com.yihaomen.mybatis.model.Student"/>    </typeAliases>    <!--指定映射器路徑-->    <mappers>        <mapper resource="com\yihaomen\mybatis\model\Student.xml"/>    </mappers></configuration>

 

 六、jdbc.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis-learn?characterEncoding=utf8jdbc.username=rootjdbc.password=tigermaxActive= 50

 

七、DAO層
/** * 這裡的@MapperScan就是上面所講的Mapper掃描器中所需要的配置,會自動組建代理程式對象。 * 注意,介面中的方法名稱要和對應的MyBatis對應檔中的語句的id值一樣,因為產生的 * 動態代理,會根據這個匹配相應的Sql語句執行。另外就是方法的參數和傳回值也需要注 * 意。介面中的方法如何定義,對應的MyBatis對應檔就應該進行相應的定義。 * 最後,標註中的userDao是用來作為Spring的Bean的id(或name)進行使用的,方便我 * 們在Service層進行注入使用。 */@MapperScanpublic interface ArticleMapper {    public List<Article> getUserArticles(int userId);}

 

 八、service層
public interface ArticleService {    public List<Article> getArticles();}
@Servicepublic class ArticleServiceImpl implements ArticleService {    @Autowired    private ArticleMapper articleMapper;    public List<Article> getArticles() {        return articleMapper.getUserArticles(1);    }}

 

 九、Controller層
@Controller@RequestMapping("/user")public class UserController {    @Autowired    private ArticleService articleService;    @RequestMapping("/list")    public ModelAndView userListAll(HttpServletRequest request, HttpServletResponse response) {        List<Article> articleList = articleService.getArticles();        ModelAndView mv = new ModelAndView("list");        mv.addObject("articles", articleList);        return mv;    }}

 

 

 https://gitee.com/huayicompany/springmvc-mybatis參考:

 [1] 《mybati實戰教程》

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.