Home > Java > javaTutorial > body text

Detailed example of springmvc+mybatis

零下一度
Release: 2017-06-23 09:23:15
Original
1999 people have browsed it

As mentioned earlier: Spring+SpringMVC+MyBatis in-depth learning and construction (13) - SpringMVC entry program (2)

1. Requirements

Use springmvc and mybatis Complete the product list query.

2. Integration ideas

System architecture of springmvc+mybatis:

The first step: Integrate dao layer

Mybatis is integrated with spring, and the mapper interface is managed through spring.

Use mapper's scanner to automatically scan the mapper interface and register it in spring.

Step 2: Integrate the service layer

Manage the service interface through spring.

Use the configuration method to configure the service interface in the spring configuration file.

Implement transaction control.

Step 3: Integrate springMvc

Since springmvc is a module of spring, there is no need to integrate.

3. Environment preparation

Database environment: mysql5.6

##java environment:

jdk1.7

MyEclipse2014

springmvc version: spring3.2

Required jar package:

Database driver package

mybatis jar package

mybatis spring integration package

log4j package

dbcp database connection pool package

spring3.2 all jar packages

jstl package

Process structure directory:

4. Integrate dao

mybatis and spring for integration.

4.1 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo
jdbc.username=root
jdbc.password=
Copy after login
4.2 log4j.properties

# Global logging configuration,建议开发环境要用debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Copy after login
4.3 sqlMapConfig.xml

Create mybatis/sqlMapConfig.xml under the classpath.

<?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> <!-- 全局setting配置,根据需要添加 --><!-- 配置别名 --><typeAliases><!-- 批量扫描别名 --><package name="joanna.yan.ssm.po"/></typeAliases><!-- 配置mapper
         由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
         但是必须遵循:mapper.xml和mapper.java文件同名且在一个目录     --><!-- <mappers></mappers> -->
 </configuration>
Copy after login
4.4 applicationContext-dao.xml

Create spring/applicationContext-dao.xml under classpath. Configuration: data source, transaction management, SqlSessionFactory, mapper scanner.

<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 
         
         
         
         
         
         
         
         
         "><!-- 加载db.properties文件中的内容,db.properties文件中的key命名要有一定的特殊规则 --><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="30"/><property name="maxIdle" value="5"/></bean><!-- sqlSessinFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /><!-- 数据库连接池 --><property name="dataSource" ref="dataSource" /></bean><!-- mapper扫描器 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开  --><property name="basePackage" value="joanna.yan.ssm.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean></beans>
Copy after login
4.5 Reverse engineering to generate po classes and mappers (i.e. single table addition, deletion, modification and query)

For details, see: Spring+SpringMVC+MyBatis in-depth learning and construction (10) ——MyBatis Reverse Engineering

#Copy the generated files to the project.

4.6 Manually define the product query mapper

For the comprehensive query mapper, there will generally be related queries, and it is recommended to customize the mapper.

4.6.1 ItemsMapperCustom.xml

sql statement:

SELECT * FROM items WHERE items.name LIKE '%Notebook%'

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="joanna.yan.ssm.mapper.ItemsMapperCustom" ><!-- 定义商品查询的sql片段,就是商品查询条件 --><sql id="query_items_where"><!-- 使用动态sql,通过if判断,满足条件进行sql拼接 --><!-- 商品查询条件通过ItemsQueryVo包装对象中itemsCustom属性传递 --><if test="itemsCustom!=null"><if test="itemsCustom.name!=null and itemsCustom.name!=&#39;&#39;">items.name LIKE '%${itemsCustom.name}%'</if></if></sql><!-- 商品列表查询 --><!-- parameterType传入包装对象(包装了查询条件)
         resultType建议使用扩展对象     --><select id="findItemsList" parameterType="joanna.yan.ssm.po.ItemsQueryVo" 
    resultType="joanna.yan.ssm.po.ItemsCustom">SELECT items.* FROM items<where><include refid="query_items_where"></include></where></select></mapper>
Copy after login
4.6.2 ItemsMapperCustom.java

public interface ItemsMapperCustom {//商品查询列表public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
Copy after login
5. Integrate service

Let spring manage the service interface.

5.1 Define service interface

package joanna.yan.ssm.service;import java.util.List;import joanna.yan.ssm.po.ItemsCustom;import joanna.yan.ssm.po.ItemsQueryVo;public interface ItemsService {//商品查询列表public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
Copy after login
package joanna.yan.ssm.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import joanna.yan.ssm.mapper.ItemsMapperCustom;import joanna.yan.ssm.po.ItemsCustom;import joanna.yan.ssm.po.ItemsQueryVo;import joanna.yan.ssm.service.ItemsService;public class ItemsServiceImpl implements ItemsService{
    
    @Autowiredprivate ItemsMapperCustom itemsMapperCustom;

    @Overridepublic List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception {//通过ItemsMapperCustom查询数据库return itemsMapperCustom.findItemsList(itemsQueryVo);
    }
}
Copy after login
5.2 Configure service in spring container (applicationContext-service.xml)

In Create spring/applicationContext-service.xml under classpath, and configure service in the file.

<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 
         
         
         
         
         
         
         
         
         "><!-- 商品管理的service --><bean id="itemsService" class="joanna.yan.ssm.service.impl.ItemsServiceImpl"/></beans>
Copy after login
5.3 Transaction Control (applicationContext-transaction.xml)

Create spring/applicationContext-service.xml under the classpath, and use the spring declarative transaction control method in the file .

<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 
         
         
         
         
         
         
         
         
         "><!-- 事务管理器
         对mybatis操作数据库事务控制,spring使用jdbc的事务控制类      --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源
             dataSource在applicationContext-dao.xml中配置了         --><property name="dataSource" ref="dataSource"/>    </bean><!-- 通知  --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 传播行为 --><!-- 可以变相的规范程序员的命名,例如以save开头,update开头等,不能想怎么命名就怎么命名 --><tx:method name="save*" propagation="REQUIRED"/><!-- 要求 --><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <!-- 支持,如果没有就算了 --><tx:method name="get*" propagation="SUPPORTS" read-only="true"/><tx:method name="select*" propagation="SUPPORTS" read-only="true"/></tx:attributes></tx:advice><!-- aop --><aop:config><!-- 切入点为joanna.yan.ssm.service.impl包下所有类的所有方法,不管里面什么参数 --><aop:advisor advice-ref="txAdvice" pointcut="execution(* joanna.yan.ssm.service.impl.*.*(..))"/></aop:config></beans>
Copy after login
6. Integrate springmvc

6.1 springmvc.xml

Create the spring/springvc.xml file under the classpath, configure the processor mapper, Adapters, view resolvers.

<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 
         
         
         
         
         
         
         
         
         "><!-- 可以扫描controller、service、...
         这里让扫描controller,指定controller的包      --><context:component-scan base-package="joanna.yan.ssm.controller"></context:component-scan><!--注解映射器 --><!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --><!--注解适配器 --><!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --><!--使用mvc:annotation-driven代替上边注解映射器和注解适配器 配置
        mvc:annotation-driven默认加载很多的参数绑定方法,
        比如json转换解析器就默认加载了,如果使用mvc:annotation-driven就不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
        实际开发时使用mvc:annotation-driven     --><mvc:annotation-driven></mvc:annotation-driven><!-- 配置视图解析器 
         解析jsp视图,默认使用jstl标签,所有classpath下得有jstl的包--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!--配置jsp路径的前缀  --><property name="prefix" value="/WEB-INF/jsp/"/><!--配置jsp路径的后缀  --><property name="suffix" value=".jsp"/></bean></beans>
Copy after login
6.2 Configuring the front-end controller

Reference entry program: Spring+SpringMVC+MyBatis in-depth learning and construction (12) - SpringMVC entry program (1)

Configure in 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 " id="WebApp_ID" version="3.0">
  <display-name>SpringMVC_MyBatis</display-name>
  <welcome-file-list><welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- springmvc前端控制器  -->
  <servlet>  <servlet-name>springmvc</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <!-- contextConfigLocation配置springmvc加载的配置文件(该配置文件中配置了处理器映射器、适配器等等) 
           如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(即springmvc-servlet.xml)      -->  <init-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:spring/springmvc.xml</param-value>  </init-param>  <!-- 表示servlet随服务启动 -->  <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>  <servlet-name>springmvc</servlet-name>  <!--Servlet拦截方式
          方式一:*.action,访问以.action结尾由DispatcherServlet进行解析
          方式二:/,所有访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析。
          使用此方式可以实现RESTful风格的url
          方式三:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,
          仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错-->  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  </web-app>
Copy after login
6.3 Write Controller (that is, Handler)

@Controllerpublic class ItemsController {
    
    @Autowiredprivate ItemsService itemsService;//商品查询http://localhost:8080/SpringMVC_MyBatis/queryItems.action@RequestMapping("/queryItems")public ModelAndView queryItems() throws Exception{//调用service查找数据库,查询商品列表List<ItemsCustom> itemsList=itemsService.findItemsList(null);        //返回ModelAndViewModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);//指定视图//        modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");//下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为modelAndView.setViewName("items/itemsList");return modelAndView;
    }
}
Copy after login
6.4 Write jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="" prefix="c" %><%@ taglib uri=""  prefix="fmt"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>查询商品列表</title></head><body> <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">查询条件:<table width="100%" border=1><tr><td><input type="submit" value="查询"/></td></tr></table>商品列表:<table width="100%" border=1><tr><td>商品名称</td><td>商品价格</td><td>生产日期</td><td>商品描述</td><td>操作</td></tr><c:forEach items="${itemsList }" var="item"><tr><td>${item.name }</td><td>${item.price }</td><td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td><td>${item.detail }</td><td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td></tr></c:forEach></table></form></body></html>
Copy after login
7. Load the spring container

Load mapper, service, and controller into the spring container.

It is recommended to use wildcard characters to load the above configuration file.

Add the spring container listener in web.xml and load the spring container.

  <!-- 加载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>
Copy after login
8. Product query debugging

Access address: http://localhost:8080/SpringMVC_MyBatis/queryItems.action

Query results:

The above is the detailed content of Detailed example of springmvc+mybatis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!