MyBatis
集成springMVC:
mybatis-3.2.2 + spring-4.0.2.RELEASE+springMVC-4.0.2.RELEASE.
如果对集成spring还不是很熟悉的可以去看前文,因为此篇文章是在前文基础上有所增加的。
通过 使用 查询部门及以下的员工来展示springMVC+mybatis的使用。
由于使用的是maven工程,所以首先要建立一个maven web工程。
数据库
web.xml
项目部署文件:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<!-- spring 配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springWithMVC.xml</param-value>
</context-param>
<!-- 配置上下文监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring MVC配置
DispatcherServlet springMVC中主控制器 又叫前端控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 springMVC的配置文件的地方 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 对静态资源的默认配置 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
POJO类
Dept.java
package com.wm.mybatis.entity;
import java.util.List;
public class Dept {
private Integer id ;
private String name ;
private String address ;
private List<Employee> employees ;
//.....
//.....setter and getter.....
}
映射文件
DeptWithSpring.xml
<?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="com.wm.mybatis.dao.IDeptWithSpringMVCMapperDao">
<resultMap type="Dept" id="resultDept">
<result property="id" column="d_id" />
<result property="name" column="d_name" />
<result property="address" column="d_address" />
<!-- 引用 一个 已存在的 resultMap Employee最基本的结果集映射 -->
<collection property="employees" ofType="Employee"
resultMap="com.wm.mybatis.dao.IEmployeeMapperDao.basicEmployee" />
</resultMap>
<select id="getDept" parameterType="map" resultMap="resultDept">
select *
from base_55demo.demo_mawei_dept d,
base_55demo.demo_mawei_employee e
where d.d_id = e.d_id
<if test="id != null">
and d.d_id = #{id}
</if>
<if test="name != null">
and d.d_name = #{name}
</if>
</select>
</mapper>
方法:getDept —> 就是要实现的方法。
Employee最基本的结果集映射在 Employee.xml里:
<!-- 最基本的Employee结果集 -->
<resultMap type="Employee" id="basicEmployee">
<id property="id" column="e_id"/>
<result property="name" column="e_name"/>
<result property="address" column="e_address"/>
</resultMap>
DAO层
IDeptWithSpringMVCMapperDao.java
package com.wm.mybatis.dao;
import java.util.Map;
import com.wm.mybatis.entity.Dept;
public interface IDeptWithSpringMVCMapperDao {
public Dept getDept(Map map);
}
service层
接口:IDeptWithSpringMVCMapperSV .java
package com.wm.mybatis.service;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.wm.mybatis.entity.Dept;
@Service
public interface IDeptWithSpringMVCMapperSV {
public Dept getDept(Map map);
}
实现类:DeptWithSpringMVCMapperSVImpl.java
package com.wm.mybatis.service;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wm.mybatis.dao.IDeptWithSpringMVCMapperDao;
import com.wm.mybatis.entity.Dept;
@Service
public class DeptWithSpringMVCMapperSVImpl implements IDeptWithSpringMVCMapperSV{
@Autowired
private IDeptWithSpringMVCMapperDao dao ;
@Override
public Dept getDept(Map map) {
return this.dao.getDept(map);
}
}
controller
控制层类:DeptController.java
package com.wm.mybatis.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.wm.mybatis.entity.Dept;
import com.wm.mybatis.service.IDeptWithSpringMVCMapperSV;
@Controller
public class DeptController {
@Autowired
private IDeptWithSpringMVCMapperSV sv ;
@RequestMapping(method=RequestMethod.POST,value="/getDept")
public ModelAndView getDept(String id , String name){
Map<String, Object> map = new HashMap<String, Object>();
if (!"".equals(id)) {
map.put("id", Integer.valueOf(id)) ;
}
if (!"".equals(name)) {
map.put("name", name) ;
}
Dept dept = this.sv.getDept(map);
return new ModelAndView("index","dept",dept);
}
@RequestMapping(method=RequestMethod.GET,value="/index")
public ModelAndView get(){
return new ModelAndView("index");
}
}
spring配置文件
springWithMVC.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: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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
<mvc:annotation-driven />
<!-- 自动扫描 注解 -->
<context:component-scan base-package="com.wm.mybatis.dao" />
<context:component-scan base-package="com.wm.mybatis.service" />
<context:component-scan base-package="com.wm.mybatis.controller" />
<!-- 导入外部配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 1、配置数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 2、配置 SqlSessionFactory -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置 数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置 mybatis 主配置文件位置 -->
<property name="configLocation" value="classpath:configure.xml" />
<!-- 配置 映射文件位置 如果mybatis的主配置文件中配置了,则可以不用配置
<property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
</bean>
<!-- 3、事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- DAO层 -->
<bean id="dao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 配置 实现 的 dao层 -->
<property name="mapperInterface" value="com.wm.mybatis.dao.IDeptWithSpringMVCMapperDao" />
<!-- 配置的 sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- service
<bean id="sv" class="com.wm.mybatis.service.DeptWithSpringMVCMapperSVImpl">
<property name="dao" ref="dao" />
</bean> -->
</beans>
使用 MapperFactoryBean,可以关联 sqlSessionFactory 和 dao层的接口,相当于原先的dao层实现类。我们就不用自己去实现 dao层,且不用自己手动式的获取session 和 关闭 session。
mybatis主配置文件
configure.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>
<!-- 配置别名 -->
<typeAliases>
<typeAlias alias="Dept" type="com.wm.mybatis.entity.Dept"/>
<typeAlias alias="Employee" type="com.wm.mybatis.entity.Employee"/>
</typeAliases>
<!-- 配置的映射文件 -->
<mappers>
<mapper resource="mapper/DeptWithSpringMVC.xml"/>
<mapper resource="mapper/Employee.xml"/>
</mappers>
</configuration>
SpringMVC的配置文件
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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 静态资源配置 -->
<mvc:resources location="/resources/" mapping="/resources/**"/>
<mvc:default-servlet-handler/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
最主要的配置已经讲 完了,下面就是写的一个简单的页面来展示效果的。
页面
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="resources/css/index.css"/>
</head>
<body>
<div class="main">
<p class="title">DEPT-EMPLOYEE</p>
<div class="part1">
<form action="getDept" method="post">
<p class="pt">部门</p>
<div class="row">
<label>部门编号:</label>
<input type="text" name="id" required="required" value="${dept.id }" />
</div>
<div class="row">
<label>部门名:</label>
<input type="text" name="name" />
</div>
<div class="row">
<input type="submit" value="查询" class="btnSubmit" />
</div>
</form>
</div>
<hr class="split" />
<div class="part2">
<p class="pt">部门信息</p>
<div>
<ul class="erow">
<li>部门号</li>
<li>部门名</li>
<li>部门地址</li>
</ul>
<ul class="erow">
<li>${dept.id }</li>
<li>${dept.name }</li>
<li>${dept.address }</li>
</ul>
</div>
<p class="pt">员工</p>
<div>
<ul class="erow">
<li>员工号</li>
<li>员工姓名</li>
<li>员工家庭地址</li>
</ul>
<c:forEach var="emp" items="${ dept.employees}">
<ul class="erow">
<li>${emp.id }</li>
<li>${emp.name }</li>
<li>${emp.address }</li>
</ul>
</c:forEach>
</div>
</div>
</div>
</body>
</html>
index.css
*{
margin: 0;
padding: 0;
background-color: beige;
}
.title{
font-family:'华文行楷';
font-size: 28px;
margin: 1em auto;
color: blue;
text-align: center;
}
.main{
margin:2em auto;
text-align:center;
width: 40em;
height: 30em;
color: hotpink;
border: 1px solid red;
border-radius: 6px;
}
.split{
clear: both;
border: 2px solid yellow;
border-style: inset ;
border-radius: 4px;
}
.pt{
text-align: left;
margin:1em;
color: aqua;
font-size: 20px;
}
.part1{
height: 6em;
clear: both;
}
.row{
margin:1em;
float: left;
}
.part2{
height:16em;
clear:both;
margin-top: .4em;
overflow: auto;
}
.erow{
clear: both;
display: block;
margin: 1em;
padding:1em;
}
li{
list-style: none;
width:6em;
float: left;
margin-left: 1em;
}
input{
width: 10em;
height: 1.8em;
padding: .3em;
}
.btnSubmit{
width: 4em;
height: 2.5em;
padding: .5em;
color: blue;
}
效果展示
首页:
查询出来后的展现效果:
至此,mybatis整合springMVC+spring已完成,其中核心部分就是 使用接口方式来实现的DAO层的实现。