Mybatis tutorial 3: Integration of mybatis and springmvc and mybatisspringmvc

Source: Internet
Author: User

Mybatis tutorial 3: Integration of mybatis and springmvc and mybatisspringmvc
1. Build a maven environment and introduce relevant jar

Refer to demo

Ii. Write 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>

 

3. xml file mvc-dispatcher-servlet.xml for spring MVC
<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>

 

4. Write the spring configuration file 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 Amework.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. propertyplaceholderpolicer "> <property name =" location "value =" classpath: jdbc. properties "/> </bean> <bean id =" dataSource "class =" com. alibaba. druid. pool. druidDataSource "init-method =" in It "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} "/> <! -- Configure the initialization size, minimum, and maximum --> <property name = "initialSize" value = "10"/> <property name = "minIdle" value = "10"/> <property name = "maxActive" value = "20"/> <! -- Configure the timeout time for obtaining connections --> <property name = "maxWait" value = "60000"/> <! -- Configure the interval for a test to detect idle connections that need to be closed, in milliseconds --> <property name = "timeBetweenEvictionRunsMillis" value = "60000"/> <! -- Configure the minimum time for a connection to survive in the pool, unit: millisecond --> <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"/> <! -- Enable PSCache, specify the PSCache size for each connection --> <property name = "poolPreparedStatements" value = "true"/> <property name = "maxPoolPreparedStatementPerConnectionSize" value = "20"/> <! -- Configure the filters intercepted by monitoring statistics, the SQL statement on the monitoring page cannot be used for statistics. --> <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 attribute specifies the connection pool to be used --> <property name = "dataSource" ref = "dataSource"/> <! -- ConfigLocation property specifies the core configuration file of mybatis --> <property name = "configLocation" value = "classpath: mybatis-config.xml"/> <property name = "mapperLocations" value = "classpath: com/yihaomen/mybatis/model /*. xml "/> </bean> </beans>
5. mybatis-config.xml documents
<? 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> <! -- This configuration enables or disables caching for global mappers --> <setting name = "cacheEnabled" value = "true"/> <! -- Allows jdbc to support generated keys. A suitable driver is required. If this parameter is set to true, the mandatory key is used, although some drivers reject compatibility, they are still valid --> <setting name = "useGeneratedKeys" value = "true"/> <! -- Configure the default executor. SIMPLE actuators have nothing special at the beginning. REUSE the executor to REUSE the pre-processing statement. BATCH executor REUSE statements and BATCH update --> <setting name = "defaultExecutorType" value = "REUSE"/> <! -- Set the timeout time, which determines the driver waits for the corresponding time of a database --> <setting name = "defaultStatementTimeout" value = "25000"/> </settings> <! -- Configure the alias --> <typeAliases> <typeAlias alias = "Student" type = "com. yihaomen. mybatis. model. Student"/> </typeAliases> <! -- Specify the er path --> <mappers> <mapper resource = "com \ yihaomen \ mybatis \ model \ Student. xml"/> </mappers> </configuration>

 

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

 

VII. DAO Layer
/*** @ MapperScan is the configuration required in the er scanner mentioned above. A proxy object is automatically generated. * Note: The method name in the interface must be the same as the id value of the statement in the corresponding MyBatis ing file, because the * dynamic proxy generated will be executed based on the matching SQL statement. In addition, the parameter and return value of the method also need to be noted * meaning. For how to define the methods in the interface, the corresponding MyBatis ing file should be defined accordingly. * Finally, the userDao in the annotation is used as the Spring Bean id (or name) for us to inject and use it at the Service layer. * // @ MapperScanpublic interface ArticleMapper {public List <Article> getUserArticles (int userId );}

 

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

 

9. Controller Layer
@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 practice tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.