SpringMVC与Mybatis配置及整合说明

SSM

咱们都知道随着技术的进步,SSM框架很是火热,那么对于咱们来讲就得搞清楚其中整合配置的流程,以便于提升咱们的开发效率而且在咱们在程序中出现Bug时能够快速定位,下面就SSM框架中的配置流程(基于配置文件)做出说明,若有不当之处,敬请你们指正。html

1.SpringMvc的配置及说明(基于XML配置文件)

首先咱们要知道SpringMVC是基于MVC的框架Web层框架,解决了前端页面和后端代码的分离问题,实现了一个请求对应一个方法前端

1.导入必要的jar包

要使用SpringMVC第一步首先要导入所必要的jar包,SpringMVC必要的jar包为: 4个spring核心包+1个日志包+2个springmvc包(web,webmvc)+1个aop注解包。java

SpringMVC导入的jar包

2.在前端页面构建一个请求

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
  <a href="${pageContext.request.contextPath }/say.do">点击发送请求say</a>
</body>
</html>

3. 配置核心控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xml="http://www.w3.org/XML/1998/namespace" 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 ">


   <!-- 配置核心控制器拦截全部的请求 -->
   <servlet>
     <servlet-name>dispatcherServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <!-- 指定配置文件的路径 -->
     <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:spring-mvc.xml</param-value>
     </init-param>
   </servlet>
   <servlet-mapping>
     <servlet-name>dispatcherServlet</servlet-name>
     <url-pattern>*.do</url-pattern>
   </servlet-mapping>

</web-app>

4.建立一个业务控制器

package com.xkt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller //组件注解
public class HelloController {

	@RequestMapping(value="/say")
	public String say(){
		System.out.println("HelloWorld!");
		return "/hello.jsp";
	}

}

5.建立Spring配置文件

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<!-- 配置组件扫描器 -->
	<context:component-scan base-package="com.xkt.controller"></context:component-scan>

</beans>

6.建立一个返回页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
  你好世界
</body>
</html>

说明: 1.SpringMVC默认状况下是线程不安全的 2.配置核心控制器后能够在web.xml拦截全部的请求,实现一个请求对应一个方法。 3.在配置文件中,咱们配置< init-parm >是但愿指定自定义的配置文件路径。若是使用框架默认的路径(放到WEB-INF下,且命名为dispatcherServlet-servlet.xml)能够不配置 4.配置< context:component-scan >是由于咱们是经过组件注解(@Controller)的方式,将类的对象加载到容器里面。因此必需要配置。mysql

2. 配置Mybatis(基于xml)及说明

咱们要知道Mybatis是一个持久层框架。可以对数据库进行增删改查操做,而且是用少许的代码就能够实现对数据库的操做,能够大大提升开发效率。web

1.导入必要jar包

1个Mybatis包+1个数据库驱动包spring

1个Mybatis包+1个数据库驱动包

2.建立DTD规范配置文件

注意:Mybatis框架的配置文件使用DTD规范文件的。因此须要经过DTD规则文件生成。(xml的约束文件DTD 以及 schema)sql

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
  
    <environments default="sms">
      <!-- 任何配置文件,的参数均可以在框架代码里面找到!! -->
      <!-- 大部分的框架,对配置文件的解释的所在类的分包的包名,configuration以及缩写、builder以及缩写 -->
      <environment id="sms">
        <transactionManager type="JDBC"></transactionManager>
        <dataSource type="POOLED">
          <!-- property 对应的就是set方法-->
          <property name="driver" value="org.gjt.mm.mysql.Driver"/>
          <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
          <property name="username" value="root"/>
          <property name="password" value="123456"/>
        </dataSource>
      </environment>
    </environments>
</configuration>

3.建立帮助类MybatisUtils

package com.xkt.utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
	
	public static final SqlSessionFactory SSF=MybatisUtils.getSSF();
	private static final ThreadLocal<SqlSession> THREAD_LOCAL=new ThreadLocal<>();

	/**
	 * 得到会话工厂
	 * @return
	 */
	private  static SqlSessionFactory getSSF() {
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			return builder.build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 得到会话
	 * @return
	 */
	public static SqlSession getSession(){
		if(THREAD_LOCAL.get()==null){
			SqlSession session = SSF.openSession();
			THREAD_LOCAL.set(session);
		}
		
		return THREAD_LOCAL.get();
	}
	
	/**
	 * 关闭会话
	 */
	public static void close(){
		if(THREAD_LOCAL.get()!=null){
			SqlSession session = THREAD_LOCAL.get();
			session.close();
			THREAD_LOCAL.remove();
		}
	}
	
	public static void main(String[] args) {
		System.out.println(MybatisUtils.getSession());
	}
	

}

4.建立实体类

package com.xkt.pojo;

public class Student {
	private String stuId;//BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '学生编号',
	private String stuName;//VARCHAR(50) NULL DEFAULT NULL COMMENT '学生名字',
	private String stuAge;//INT(11) NULL DEFAULT NULL COMMENT '学生年龄',
	private String stuPassword;//VARCHAR(50) NULL DEFAULT NULL COMMENT '密码',
	public String getStuId() {
		return stuId;
	}
	public void setStuId(String stuId) {
		this.stuId = stuId;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getStuAge() {
		return stuAge;
	}
	public void setStuAge(String stuAge) {
		this.stuAge = stuAge;
	}
	public String getStuPassword() {
		return stuPassword;
	}
	public void setStuPassword(String stuPassword) {
		this.stuPassword = stuPassword;
	}
}

5.建立映射接口

packagecom.xkt.mapper;

import com.xkt.pojo.Student;

public interface StudentMapper {
	
	/**
	 * 插入学生
	 * @param student
	 * @return
	 */
	int insert(Student student);

}

6.建立并加载映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="com.xkt.mapper.StudentMapper">
   
   <insert id="insert">
    INSERT INTO tb_student	(stu_name, stu_age, stu_password) VALUES (#{stuName}, #{stuAge}, #{stuPassword})
   </insert>
</mapper>

7.测试插入数据

package com.xkt.test.mapper;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import  com.xkt.mapper.StudentMapper;
import  com.xkt.pojo.Student;
import  com.xkt.utils.MybatisUtils;

public class StudentMapperTest {
	
	@Test
	public void insert(){
		//得到操做对象
		SqlSession session = MybatisUtils.getSession();
		StudentMapper studentMapper = session.getMapper(StudentMapper.class);
		Student student=new Student();
		student.setStuName("张三");
		int count = studentMapper.insert(student);
		System.out.println(count);
		session.commit();
		MybatisUtils.close();
		
	}

}

3.SpringMVC整合Mybatis(基于xml)

SpringMVC整合Mybatis就是,就是让Mybatis抛弃本身实现的数据源,再使用Spring提供的数据源。(由于咱们要让Mybatis使用Spring框架里面的事务代理机制,Spring框架的事务代理依赖Spring JDBC里面的数据源)数据库

1.导入须要的jar包

整合SpringMVC与Mybatis须要的jar包

2.配置文件按照以下步骤配置

第一步:配置数据源

第二步:得到会话工厂

第三步:得到操做对象,而且注入到Spring容器里面

第四步;配置事务代理

<?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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


	<!-- 1.配置数据源 -->
	<bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<!-- 四要素 -->
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/sms" />
		<property name="username" value="root" />
		<property name="password" value="1234" />

	</bean>

	<!-- 2.配置会话工厂 -->
	<!-- 默认状况下:mybatis是不支持spring的数据源的 -->
	<!-- 问题:那么咱们如何可让mybatis支持spring的数据源呢? -->
	<!-- 答:须要一个整合包 mybatis-spirng.jar
	SqlSessionFactoryBean:做用就是让Mybatis能够经过Spring的数据源建立会话工厂的
	 -->
	<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	   <!-- 指定数据源 -->
	   <property name="dataSource" ref="dataSource"></property>
	   <!-- 加载映射文件的路径 -->
	   <property name="mapperLocations" value="classpath:com/xkt/mapper/xml/*Mapper.xml"></property>
	</bean>
	
	<!-- 3.配置扫描器,将映射接口的动态对象建立,而且注入到spring容器里面 -->
	<!-- 默认状况下:spring是不支持经过接口建立对象!!而Mybatis就是经过接口建立对象的
	     问题:Spring必需要实现类建立能够注入到容器,而Mybatis就是使用接口建立动态对象的。不能兼容Spring的要求。怎么办呢?
	     答:整合包提供了一个映射接口扫描器,用于经过映射接口建立了对象,而且能够建立的对象注入到容器里面
	     -根据表述扫描器必须要的两个条件
	     1.须要会话工厂
	     2.必需要指定映射接口的路径
	 -->
	 
	 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	    <property name="basePackage" value="com.xkt.mapper"></property>
	    <!-- 指定扫描注解 -->
	    <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"></property>
	 </bean>
	 
	
	<!-- 4.配置事务代理,编程式事务 -->
	<!-- 注意:Mybatis是的spring jdbc的事务代理 -->
	<!-- 建立事务代理对象 -->
	<bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
	   <!-- 指定数据源 -->
	    <property name="dataSource" ref="dataSource"></property>
	 </bean>
	 
	 <!-- 启动事务代理 -->
	<tx:annotation-driven/>

</beans>
相关文章
相关标签/搜索