Spring与Mybatis结合例子详解

本文深入探讨了Spring MVC与MyBatis的整合技术,从配置文件到核心组件,详细阐述了如何实现数据操作与页面展示的无缝对接。通过实际案例,展示了如何在Web应用中高效地运用这两种强大的框架。

工程目录结构如下:

  

数据表:


配置:

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>springMybatis</display-name>

<!-- 配置文件位置,默认为/WEB-INF/applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 字符集过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 上下文Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- servlet控制跳转 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:context-dispatcher.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<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>
</web-app>  


web.xml中引用的配置文件applicationContext.xml和context-dispatcher.xml定义如下:

1.应用上下文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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" 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.0.xsd  
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 引入jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!--创建jdbc数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
	</bean>

	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 创建SqlSessionFactory,同时指定数据源 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 可通过注解控制事务 -->
	<tx:annotation-driven />

	<!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.example.spring.mapper" />
	</bean>

</beans>  

其中,引用了jdbc.properties文件。没有必要在 Spring 的 XML 配置文件中注册所有的映射器,可以使用一个 MapperScannerConfigurer , 它 将 会 查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean,此处是自动查找com.example.spring.mapper包下的映射器。

2.上下文调度器context-dispatcher.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	 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-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-3.0.xsd">

	<!-- 使用注解的包,包括子集 -->
	<context:component-scan base-package="com.example.spring" />
	<!-- 通过注解,把URL映射到Controller上,该标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
	<mvc:annotation-driven />
	<!-- 视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
		p:defaultEncoding="UTF-8" />
</beans>  

其中,视图解析器中定义了controller访问页面的默认前缀和后缀。

jdbc.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=root

LoginController.java:

package com.example.spring.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.spring.entity.Student;
import com.example.spring.service.StudentService;

@Controller
@RequestMapping(value = "background")
public class LoginController {
	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "to_login")
	public ModelAndView toLogin(HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Student> result = studentService.findAll();
		map.put("result", result);
		return new ModelAndView("background/student", map);
	}
}

其中,注解@Controller对应表现层的Bean,也就是Action;@RequestMapping在类前面表示访问controller时自动添加上的url前缀,在方法前面表示访问方法时自动添加上的前缀;如果StudentService.java中类前加有注解@Repository(value="studentServ"),则@Autowired等同于@Resource(name="studentServ"),相当于实例化了此接口。

如果去掉@Controller注解,运行警告:No mapping found for HTTP request with URI [/springMybatis/background/to_login] in DispatcherServlet with name 'spring'

Student.java:

package com.example.spring.entity;

public class Student {
	private int id;
	private String name;
	private int age;
	private String major;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getMajor() {
		return major;
	}

	public void setMajor(String major) {
		this.major = major;
	}

}
StudentMapper.java:

package com.example.spring.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.example.spring.entity.Student;

public interface StudentMapper {
	@Select(value = "${sql}")
	@Results(value = { @Result(id = true, property = "id", column = "id"),
			@Result(property = "name", column = "s_name"), 
			@Result(property = "age", column = "s_age"),
			@Result(property = "major", column = "s_major") })
	public List<Student> operateReturnBeans(@Param(value = "sql") String sql);
}

其中,注解@Select表示它注解的方法会执行一个sql查询语句,此处可以替换为@Select("SELECT * FROM tb_student"),删除方法里面的参数,同样的效果。如果想通过id查询:@Select("SELECT * FROM tb_student WHERE id = #{id}")
operateReturnBeans(@Param(value = "id") int id);@Results是对返回结果字段的注解,如果使用的字段与表字段名相同,此注解可省略。

如果去掉@Param注解,运行异常:org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'sql' in 'class java.lang.String'

StudentService.java:

package com.example.spring.service;

import java.util.List;

import com.example.spring.entity.Student;

public interface StudentService {
	/**
	 * 查询所有
	 */
	public List<Student> findAll();
}
StudentServiceImpl.java:

package com.example.spring.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.spring.entity.Student;
import com.example.spring.mapper.StudentMapper;
import com.example.spring.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;

	@Override
	public List<Student> findAll() {
		String sql = "SELECT * FROM tb_student";
		return studentMapper.operateReturnBeans(sql);
	}

}

其中,注解@Service对应的是业务层Bean

关于注解,可参考:Spring常用注解官方释义

其他参考:

http://blog.youkuaiyun.com/jbjwpzyl3611421/article/details/18700335

http://www.cnblogs.com/xdp-gacl/p/3495887.html

student.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>
	<c:forEach items="${result}" var="item">  
        ${item.id}--${item.name}--${item.age}--${item.major}<br />
	</c:forEach>
</body>
</html>
其中,<c:forEach>是JSTL语法,在controller中map.put("result", result);里面的内容传过来,这样就可解析出”result"内容了。
运行结果:


参考:Spring MVC整合Mybatis实例    demo源码

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzyjr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值