您的位置:首页 > 编程语言 > Java开发

Spring4+SpringMVC4+MyBatis3.2整合

2015-11-25 21:27 495 查看

1、基本概念

1.1、Spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.2、SpringMVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

1.3、MyBatis

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。


2、具体整合

首先看看 web.xml的详细配置 解释说明就放在源代码里面了

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd"> 
	<!-- 加载Spring容器配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 设置Spring容器加载所有的配置文件的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:config/spring-*.xml</param-value>
	</context-param>

	<!-- 配置SpringMVC核心控制器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 -->  
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:config/spring-mvc.xml</param-value>
		</init-param>
		<!-- 启动加载一次 -->  
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!--为DispatcherServlet建立映射 -->
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- 解决工程编码过滤器 -->
	<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>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


2.1Spring配置文件

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.0.xsd  http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 
	<!-- 注解扫描包 -->
	<context:component-scan base-package="weixin.zzq" />

	<!-- 开启注解 -->
	<mvc:annotation-driven />

	<!--
		配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd
	-->
	<mvc:resources mapping="/img/**" location="/img/" />
	<mvc:resources mapping="/js/**" location="/js/" />
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="/html/**" location="/html/" />

	<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>


2.2Spring整合Mybatis配置文件

<?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-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/tx 	 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> 
	<!-- 1. 数据源 : DriverManagerDataSource -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/weixin" />
		<property name="username" value="" />
		<property name="password" value="" />
	</bean>

	<!--
		2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源

		MyBatis定义数据源,同意加载配置
	-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:config/mybatis-config.xml" /> 
	</bean>

	<!--
		3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory

		basePackage:指定sql映射文件/接口所在的包(自动扫描)
	-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="weixin.zzq.mapper"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>

	<!--
		4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
	-->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 5. 使用声明式事务
		 transaction-manager:引用上面定义的事务管理器
	 -->
	<tx:annotation-driven transaction-manager="txManager" />

</beans>

2.3Mybatis配置文件

<?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="Email" type="weixin.zzq.model.Email" />
	</typeAliases>
	<!-- 实体接口映射资源 -->
	<!--
		说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml
	-->
	<!-- <mappers>
		<mapper resource="com/tgb/mapper/userMapper.xml" />
	</mappers> -->

</configuration>


配置文件 完毕

3、下面是分层结构Java代码和MybatisSQL配置

3.1model

public class Email {
	private Integer id;// 主键
	private String youremail;// 发送方email
	private String formemail;// 接收方eamil
	private String message;// 发送内容
	private String beizhu;// 备注
	private String dingshi;// 定时
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getYouremail() {
		return youremail;
	}
	public void setYouremail(String youremail) {
		this.youremail = youremail;
	}
	public String getFormemail() {
		return formemail;
	}
	public void setFormemail(String formemail) {
		this.formemail = formemail;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getBeizhu() {
		return beizhu;
	}
	public void setBeizhu(String beizhu) {
		this.beizhu = beizhu;
	}
	public String getDingshi() {
		return dingshi;
	}
	public void setDingshi(String dingshi) {
		this.dingshi = dingshi;
	}
	
}


3.2mapper接口(此接口内方法要对应Mybatis配置文件的SQL搜索)

public interface EmailMapper {//此处展示部分方法
	 void save(Email email);
	 Email findById(int id);
	 void delete(int id); 
}


3.3mapper类对应的Mybatis配置文件

<?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="weixin.zzq.mapper.EmailMapper">  
 <resultMap type="weixin.zzq.model.Email" id="Email">  
    <id column="ID" jdbcType="INTEGER" property="id"/>  
    <result column="YOUREMAIL" jdbcType="VARCHAR" property="youremail"/>  
    <result column="FORMEMAIL" jdbcType="VARCHAR" property="formemail"/>  
    <result column="MESSAGE"   jdbcType="VARCHAR" property="message"/>  
    <result column="BEIZHU"    jdbcType="VARCHAR" property="beizhu"/>  
    <result column="DINGSHI"   jdbcType="VARCHAR" property="dingshi"/>  
  </resultMap>    
  
  <select id="selectID" parameterType="int" resultMap="Email">  
    select ID,YOUREMAIL,FORMEMAIL,MESSAGE,BEIZHU,DINGSHI from Email where ID=#{_parameter}  
  </select> 
   <select id="findAll" resultMap="Email">  
    select ID,YOUREMAIL,FORMEMAIL,MESSAGE,BEIZHU,DINGSHI from Email 
  </select>   
    
  <insert id="save" parameterType="Email">  
  insert into Email(YOUREMAIL,FORMEMAIL,MESSAGE,BEIZHU,DINGSHI) values(#{youremail},#{formemail},#{message},#{beizhu},#{dingshi})  
  </insert> 
   
   <update id="update" parameterType="Email">  
   update Email set YOUREMAIL=#{youremai},FORMEMAIL=#{formemail},MESSAGE=#{message},BEIZHU=#{beizhu},DINGSHI=#{dingshi} where ID=#{id}
  </update> 
   
  <delete id="deleteID" parameterType="int">  
    delete from Student where ID = #{id}  
  </delete>  
</mapper>



到这里基本重要的配置文件已经完毕

下面就是 service层和view层 此处只展示代码

3.4service层

public interface EmailService extends EmailMapper{

}


3.5service实现层

@Service
@Transactional  //此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
public class EmailServuceImpl implements EmailService{
    @Resource
    private EmailMapper emailMapper;
	public void save(Email email) {
		emailMapper.save(email);
	}

	public Email findById(int id) {
		return emailMapper.findById(id);
	}
	public List<Email> findAll() {
		
		return emailMapper.findAll();
	}

	public void delete(int id) {
		 emailMapper.delete(id);
	}

}


3.6view层controller类

@Controller
public class EmailController {
	@Autowired
	private EmailService emailService;
     @RequestMapping("/hello")
     public String hello(){
    	 return "helloworld";
     }
项目到这里就整合完毕了 其实和SSH大同小异


4、下面是项目结构截图



最近在开发微信公众号 大家可以去 关注一下哈 公众号是 强子公众

二维码



谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: