Spring MVC+MyBatics+Spring集成小例子

散仙,在前面的博客中写过一篇,Spirng MVC+Hibernate+Spring集成小例子,鉴于各个公司在持久层多样化的选择,那么本篇呢,散仙来简单介绍下Spring MVC+MyBatics+Spring三者之间的整合,因为这也算目前大多数公司,使用的比较多的一种组合,当然也有基于SSH的架构Spring+Struts2+Hibernate,抛开这两种组合的优劣点,今天我们主要介绍的是怎么组合使用,所以关于框架本身的优劣点,就不在这里加以评论了。

散仙的开发环境如下:


名称 描述
Web容器 Tomcat7.0
IDE工具 Myeclipse10.1
平台 Windows
语言 JAVA
JDK 1.7
数据库 MySQL5.1
Sping 3.2(非Myeclipse自带,需要下载)
MyBatics 3.2(需下载)
Jquery 1.7.1
人力道具 屌丝软件工程师一名


项目背景概况,此项目为了模拟开发中的实际场景,使用了2张表,具有主外键关系,一个是主表Person,另一个从表Country,比上一次的单表的增删改查骚加复杂,实为新手练手的一个好例子。
下面是功能描述:
功能 描述
查询功能 默认情况下显示所有Person信息,需含有外键表的Country的name信息
增加功能 在首页上点击添加信息,跳转页面,Country信息需用下拉框显示,后台添加成功后,需要用以ajax的形式,返回响应,提示添加成功
修改功能 可以对对应的Person信息进行修改,注意下拉框与修改的Person的对应
删除功能 可以在首页上对对应的Person信息进行删除


关于在IDE中,怎么让MyBatics的xml文件字段提示,可以参考散仙的上篇文章配置Mybatics的mapper文件提示
实体类person的映射配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="dao.PersonMapper">

   
  <!-- 返回关联映射 -->
  <resultMap type="Person" id="mylist" >
   <id property="id" column="id"/>
   <result property="name" column="name"/>
   <result property="age" column="age"/>
   <!-- 支持嵌套类 -->
    <association property="country" javaType="Country" column="cid">
  <id property="id" column="cid"/>
  <result property="cname" column="cname"/>
  </association>
  </resultMap>
  
  <!-- 查询所有 -->
     <select id="getAll" resultType="Person" resultMap="mylist">
  select 
  
   p.id as id,p.`name` as name ,p.age  as age ,
   c.cname as cname   ,c.id as cid 
  
   from
   
   person p,country c 

   where p.cid=c.id  
   order by id
  </select>

 <!-- 保存 -->
  <insert id="save"> 
insert into person(name,age,cid) 
values(#{name},#{age},#{country.id}) 
</insert>
<!-- 删除 -->
<delete id="delete">
delete from person where id=#{id}
</delete>


<!-- 更新的信息 -->
<update id="update">

update person set name=#{name},age=#{age},cid=#{country.id} where id=#{id} 
</update>
<!-- 获取单个实体类的信息 -->
<select id="get" resultType="Person" resultMap="mylist"  >
select *from  person where id=#{id}
</select>

<!-- 统计分页个数 
<select id="count" resultType="int">
  
    select count(*) from classes

</select>
-->
<!-- Oracle查询分页实体类集合
<select id="pageList" parameterType="java.util.Map" resultType="Classes">
 
  select *from  (select rownum a, classes.* from classes ) c
  where  c.a
  between   #{offset} and  #{pageSize} 
</select>
  -->
  
  <!-- MySQL 分页 
  <select id="pageList" parameterType="java.util.Map" resultType="Classes">
 
   select *from classes order by id  limit #{offset},#{pageSize}
  </select>
   -->
   
   <!-- SQL Server分页   
   
   注意SQL Server 分页不支持?占位符所以得用
   $符进行替代换位
   
    <select id="pageList" parameterType="java.util.Map" resultType="Classes">
      
   select  top  ${offset}  *   from Classes
   where id not in(select top  ${pageSize}  id from Classes)
  
  </select>
   -->
   
</mapper>

实体类country的映射配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="dao.CountryMapper">


  <!-- 返回关联映射 -->
  <resultMap type="Country" id="mylist" >
   <id property="id" column="id"/>
   <result property="cname" column="cname"/><!-- 与别名对应 -->
    
  </resultMap>
  
  <!-- 查询所有 -->
     <select id="getAll" resultType="Country" resultMap="mylist">
  select 
  
   id,cname
  
   from
   
   country 
 
  </select>




<!-- 统计分页个数 
<select id="count" resultType="int">
  
    select count(*) from classes

</select>
-->
<!-- Oracle查询分页实体类集合
<select id="pageList" parameterType="java.util.Map" resultType="Classes">
 
  select *from  (select rownum a, classes.* from classes ) c
  where  c.a
  between   #{offset} and  #{pageSize} 
</select>
  -->
  
  <!-- MySQL 分页 
  <select id="pageList" parameterType="java.util.Map" resultType="Classes">
 
   select *from classes order by id  limit #{offset},#{pageSize}
  </select>
   -->
   
   <!-- SQL Server分页   
   
   注意SQL Server 分页不支持?占位符所以得用
   $符进行替代换位
   
    <select id="pageList" parameterType="java.util.Map" resultType="Classes">
      
   select  top  ${offset}  *   from Classes
   where id not in(select top  ${pageSize}  id from Classes)
  
  </select>
   -->
   
</mapper>

Mybatics通用DAO的写法
package commons;

import java.io.Serializable;
import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
 * 操作mybatis的工具接口
 * 
 * */
public class MyBatisDao extends SqlSessionDaoSupport {
	
	   /**
	    * @param key 命名空间+id值
	    * @param o 需要进行保存的实体类
	    * 保存的方法
	    * */
	   public void save(String key,Object o){
		   
		   this.getSqlSession().insert(key, o);
	   }
	   
	   /**
	    * 删除的方法
	    * */
	   public void delete(String key,Object o){
		   this.getSqlSession().delete(key, o);
	   }
	   
	   /**
	    * 修改的方法
	    * */
	   public void update(String key,Object o){
		   this.getSqlSession().update(key, o);
		   
	   }
	   
	   /**
	    * 根据ID 查询单个实体类
	    * */
	   public <E> E get(String key,Serializable id){
		   return this.getSqlSession().selectOne(key,id);
	   }
	   
	   /***
	    * 查询实体类集合
	    * 
	    * */
	   public <E> List<E> getAll(String key){
		   
		   return this.getSqlSession().selectList(key);
	   }
	   
	   /***
	    * 查询实体类的总个数
	    * */
	   public int count(String key){
		   return this.getSqlSession().selectOne(key);
	   }
	   /**
	    * 查询总集合数
	    * 
	    * */
       public <E> List<E> pageList(String key,Object o){
    	   return this.getSqlSession().selectList(key,o);
       }
}


Spirng注解控制器类

package controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 
import org.springframework.stereotype.Controller;
 
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 

import com.google.gson.Gson;
import commons.MyBatisDao;

 

import dao.CountryDao;
import dao.PersonDao;
import entity.Country;
import entity.Person;

/**
 * @author 秦东亮
 * 技术群:324714439
 * 
 * 
 * */
@Controller
public class PersonController {
 
	@Resource(name="personDao")
	  private PersonDao personDao;
 
	 public PersonDao getPersonDao() {
		return personDao;
	}
 
	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
		 
	}
	@Resource(name="countryDao")
	private CountryDao countryDao;
	
 
	public CountryDao getCountryDao() {
		return countryDao;
	}
    
	@Resource(name="dao")
	 private MyBatisDao dao;
	 
	
	public MyBatisDao getDao() {
		return dao;
	}

	public void setDao(MyBatisDao dao) {
		this.dao = dao;
	}

	public void setCountryDao(CountryDao countryDao) {
		this.countryDao = countryDao;
	}

	/**
	 * 输出所有的用户信息
	 * 
	 * **/
	@RequestMapping( value="/showAll")
	public String showAll(HttpServletRequest request)throws Exception{
		  
		//MyBatisDao dao=new MyBatisDao();
//		/request.setAttribute("plist", personDao.find(" from Person "));
		request.setAttribute("plist",dao.getAll("dao.PersonMapper.getAll"));
		 
		 return "showAll";
	 }
	
	/**
	 * 输出所有的国家信息
	 * 
	 * **/
	@RequestMapping( value="/add")
	public String add(HttpServletRequest request)throws Exception{
		 
		 
		//request.setAttribute("clist", countryDao.find(" from Country "));
		 request.setAttribute("clist", dao.getAll("dao.CountryMapper.getAll"));
		 
		 return "adda";
	 }
	
	 /**
	  * 删除的方法
	  * */
	@RequestMapping( value="/delete")
	public String delete(HttpServletRequest request)throws Exception{
		 
		 int id=Integer.parseInt(request.getParameter("id"));
		 //personDao.delete(personDao.get(id));
		 dao.delete("dao.PersonMapper.delete", id);
		 return "redirect:/showAll";
	 }
	
	 /**
	  * 删除的方法
	  * request域的写法
	  * */
	@RequestMapping( value="/update")
	public String update(HttpServletRequest request)throws Exception{
		 
		 int id=Integer.parseInt(request.getParameter("id"));
		  
		 
		 //request.setAttribute("p", personDao.get(id));
		  request.setAttribute("p", dao.get("dao.PersonMapper.get", id));
		  request.setAttribute("clist", dao.getAll("dao.CountryMapper.getAll"));
		  
		 //request.setAttribute("clist", countryDao.find(" from Country "));
		 
		 
		 
		 return "update";
	 }
	
	
	 /**
	  * 更新的操作
	  * 封装成实体类的写法
	  * */
	@RequestMapping( value="/sup",method=RequestMethod.POST)
	public String sup(Person person,HttpServletRequest request){
		 
		try{
			
			//personDao.update(person);
			dao.update("dao.PersonMapper.update", person);
//		 System.out.println("111");
	//	System.out.println(person.getName());
			//System.out.println(person.getCountry().getId());
			//System.out.println(request.getParameter("name"));
		 
		}catch (Exception e) {
			 e.printStackTrace();
		}
		 return "redirect:/showAll";
	 }
	
	/**
	 * 保存一条数据
	 * 没有使用实体类自动封装的功能
	 * 
	 * **/

	@RequestMapping( value="/save",method=RequestMethod.POST)
	 
	public void  save(HttpServletRequest request,HttpServletResponse response)throws Exception{
	 
	 
	//   personDao.save(person);//保存成功
		 
 	 Person person=new Person();
 	 person.setAge(Integer.parseInt(request.getParameter("age")));
 	 person.setName(request.getParameter("name"));
 	 Country c=new Country();
 	 c.setId(Integer.parseInt(request.getParameter("cid")));
 	 person.setCountry(c);
 	 personDao.save(person);
		
 	//System.out.println("cid :  "+request.getParameter("cid"));
    Gson g=new Gson();
//    List<String> list=new ArrayList<String>();
//    list.add("A");
//    list.add("B");
//    list.add("C");
//    list.add("D");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=utf-8");
    //response.getWriter().write(g.toJson(list)); 
    response.getWriter().write(g.toJson("添加成功!")); 
	//	response.getWriter().write("1");
	 
		   
				
	 }


	/**
	 * 保存一条数据
	 * 基于ajax的json自动封装的
	 * 实体类
	 * 注意有嵌套类时的
	 * 写法"county.id"
	 * 
	 * **/

	@RequestMapping( value="/savetwo",method=RequestMethod.POST)
	 
	public void  savetwo(Person person,HttpServletRequest request,HttpServletResponse response)throws Exception{
	 
	   //personDao.save(person);//保存成功
		 
		//System.out.println(person.getName());
		dao.save("dao.PersonMapper.save", person);
		
	//	System.out.println(person);
 	//System.out.println("cid :  "+request.getParameter("cid"));
    Gson g=new Gson();
//    List<String> list=new ArrayList<String>();
//    list.add("A");
//    list.add("B");
//    list.add("C");
//    list.add("D");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=utf-8");
    //response.getWriter().write(g.toJson(list)); 
    response.getWriter().write(g.toJson("添加成功!")); 
	//	response.getWriter().write("1");
	 
		   
				
	 }




}



Spring的servlet的xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName" 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-3.0.xsd  
       http://www.springframework.org/schema/mvc  
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
       
        ">

 <!-- 注解扫描包 -->  
    <context:component-scan base-package="controller" />  
  
    <!-- 开启注解 -->  
    <mvc:annotation-driven />  
   
   
   <!--  
    <bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
				<value>text/plain;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
	-->
	 <!-- 
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
  <property name="mediaTypes">  
    <map>  
      <entry key="atom" value="application/atom+xml"/>  
      <entry key="html" value="text/html"/>  
      <entry key="json" value="application/json"/>  
    </map>  
  </property>  
  <property name="viewResolvers">  
    <list>  
      <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>  
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"/>  
        <property name="suffix" value=".jsp"/>  
      </bean>  
    </list>  
  </property>  
  <property name="defaultViews">  
    <list>  
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />  
    </list>  
  </property>  
</bean>  

  -->
  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    
    
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
      <!-- 处理器映射 -->
    <!--   <bean class="com.qin.annocontroller.HelowWorld" ></bean> -->
      <!-- 注解使用的 HandlerMapping -->
      <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
      <!-- 注解使用的 HandlerAdapter -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
     <!-- 支持json返回   -->
        
      
      </bean>
         <!-- 配置控制器里的注入 -->
       <bean id="dao" class="commons.MyBatisDao">  
     <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
    </bean>
   
    <!-- 声明DispatcherServlet不要拦截下面声明的目录 -->  
    <mvc:resources location="/jquery/" mapping="/jquery/**" />  
   <!--   <mvc:resources location="/jsp/" mapping="/jsp/**" />  -->
</beans>





你可能感兴趣的:(spring,mvc,mybatis)