首页 > 代码库 > MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)
  首先,需要知道Eclipse如何创建Dynamic Web Project for Maven,我们首先需要知道如何用Eclipse创建动态部署的Maven Web-app 项目.参考以下链接的博客:http://blog.csdn.net/smilevt/article/details/8215558.

  构建完之后:实现具体的增删改查,不去部署Web war的时候我们用Junit单元测试CRUD功能。代码如下:
 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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd       
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!-- 引入jdbc.properties -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 扫描文件  自动将service层和dao层组件注入 -->
	<context:component-scan base-package="com.clark.service"></context:component-scan>
	<context:component-scan base-package="com.clark.dao"></context:component-scan>
</beans>
jdbc.properties配置文件
jdbc_driverClassName=oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@172.30.0.125:1521:oradb01
jdbc_username=settlement
jdbc_password=settlement
mybatis-config.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>
		<!-- give a alias for model -->
		<typeAlias alias="goods" type="com.clark.model.Goods"></typeAlias>
	</typeAliases>
	<mappers>
		<!-- <mapper resource="com/clark/model/goodsMapper.xml" /> -->
	</mappers>
</configuration>
spring-mybatis.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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    
    <bean id="goodsServiceImpl" class="com.clark.service.impl.GoodsServiceImpl">
    </bean>
	    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	    <property name="driverClassName">
	      <value>${jdbc_driverClassName}</value>
	    </property>
	    <property name="url">
	      <value>${jdbc_url}</value>
	    </property>
	    <property name="username">
	      <value>${jdbc_username}</value>
	    </property>
	    <property name="password">
	      <value>${jdbc_password}</value>
	    </property>
	    <!-- 连接属性 -->
	    <property name="connectionProperties">
	      <value>clientEncoding=UTF-8</value>
	    </property>
  	</bean>
     
    <!-- mybatis文件配置,扫描所有mapper文件 -->
      <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:mybatis-config.xml"
          p:mapperLocations="classpath:mapper/*.xml"/><!-- configLocation为mybatis属性 mapperLocations为所有mapper-->
       
    <!-- spring与mybatis整合配置,扫描所有dao.impl -->
 		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        	p:basePackage="com.clark.dao.impl"
        	p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
  		
    <!-- 对数据源进行事务管理 -->
  		<bean id="transactionManager"
        	class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        	p:dataSource-ref="dataSource"/>
</beans>
goodsMapper.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="clark">
	<!-- 将db查询出来的结果映射到Model Goods -->
	<resultMap type="com.clark.model.Goods" id="t_good">
		<id column="id" property="id"/>
		<result column="cate_id" property="cateId"/>
		<result column="name" property="name"/>
		<result column="price" property="price"/>
		<result column="description" property="description"/>
		<result column="order_no" property="orderNo"/>
		<result column="update_time" property="updateTime"/>
	</resultMap>
	<!-- 根据id查询 返回Goods类型  <typeAlias alias="goods" type="com.clark.model.Goods"></typeAlias>-->
	<!--resultMap 和   resultType的使用区别-->
	<select id="selectGoodById" parameterType="int" resultMap="t_good">
		select id,cate_id,name,price,description,order_no,update_time 
		from goods where id = #{id}
	</select>
	<!-- 查询所有Goods 返回resultMap类型-->
	<select id="selectAllGoods" resultMap="t_good">
		select id,cate_id,name,price,description,order_no,update_time from goods
	</select>
	<!-- 指定parameterType=map 其中map的形式为Map<String,PageBean> map-->
	<select id="selectGoodsByPage" resultMap="t_good" parameterType="map">
		<!-- order by id asc是指对查询后的结果进行升序排序 -->
		<![CDATA[ 
			select * from 
			(select g.*,rownum rn from (select * from goods) g where 1=1 and rownum <= #{pageBean.endNumber}) 
			where rn >= #{pageBean.startNumber}
			order by id asc
		]]>
	</select>
	<!-- 新增Goods 参数类型为Goods-->
	<insert id="insertGood" parameterType="goods">
		insert into goods(id,cate_id,name,price,description,order_no,update_time)  
		values(#{id},#{cateId},#{name},#{price},#{description},#{orderNo},#{updateTime})
	</insert>
	<!-- 更新Goods 参数类型为Goods-->
	<update id="updateGood" parameterType="goods">
		update goods g 
		set g.name = #{name},g.order_no =#{orderNo}
		where g.id = #{id}
	</update>
	<!-- 删除Goods 参数类型为int-->
	<delete id="deleteGood" parameterType="int">
		delete from goods g 
		where g.id = #{id}
	</delete>
</mapper>
Model ----Goods.java
package com.clark.model;

import java.util.Date;

public class Goods {
	private Integer id;
	private Integer cateId;
	private String name;
	private double price;
	private String description;
	private Integer orderNo;
	private Date updateTime;
	
	public Goods(){
		
	}
	
	public Goods(Integer id, Integer cateId, String name, double price,
			String description, Integer orderNo, Date updateTime) {
		super();
		this.id = id;
		this.cateId = cateId;
		this.name = name;
		this.price = price;
		this.description = description;
		this.orderNo = orderNo;
		this.updateTime = updateTime;
	}


	public Integer getId() {
		return id;
	}


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


	public Integer getCateId() {
		return cateId;
	}


	public void setCateId(Integer cateId) {
		this.cateId = cateId;
	}


	public String getName() {
		return name;
	}


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


	public double getPrice() {
		return price;
	}


	public void setPrice(double price) {
		this.price = price;
	}


	public String getDescription() {
		return description;
	}


	public void setDescription(String description) {
		this.description = description;
	}


	public Integer getOrderNo() {
		return orderNo;
	}


	public void setOrderNo(Integer orderNo) {
		this.orderNo = orderNo;
	}


	public Date getTimeStamp() {
		return updateTime;
	}


	public void setTimeStamp(Date updateTime) {
		this.updateTime = updateTime;
	}


	@Override
	public String toString() {
		return "[goods include:Id="+this.getId()+",name="+this.getName()+
				",orderNo="+this.getOrderNo()+",cateId="+this.getCateId()+
				",updateTime="+this.getTimeStamp()+"]";
	}
}
PageBean.java
package com.clark.util;
//模拟的一个分页对象PageBean
public class PageBean {
	//开始数
	private Integer startNumber;
	//结束数
	private Integer endNumber;
	
	public PageBean(){
		
	}
	public PageBean(Integer startNumber, Integer endNumber) {
		super();
		this.startNumber = startNumber;
		this.endNumber = endNumber;
	}
	public Integer getStartNumber() {
		return startNumber;
	}
	public void setStartNumber(Integer startNumber) {
		this.startNumber = startNumber;
	}
	public Integer getEndNumber() {
		return endNumber;
	}
	public void setEndNumber(Integer endNumber) {
		this.endNumber = endNumber;
	}
}
GoodsDao.java
package com.clark.dao;

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

import com.clark.model.Goods;
import com.clark.util.PageBean;

public interface GoodsDao {
	
	public int insertGoods(Goods goods);
	
	public int updateGoods(Goods goods);
	
	public int deleteGoods(Integer id);
	
	public Goods findGoodById(Integer id);
	//find all
	public List<Goods> findAllGoods();
	
	public List<Goods> findGoodsByPage(Map<String,PageBean> map);
	
}
GoodsDaoImpl.java
package com.clark.dao.impl;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.clark.dao.GoodsDao;
import com.clark.model.Goods;
import com.clark.util.PageBean;
@Service
public class GoodsDaoImpl implements GoodsDao{
	//注意SqlSessionFactory是mybatis操作数据库的session对象
	@Autowired
	private SqlSessionFactory sessionFactory;
	
	@Override
	public int insertGoods(Goods goods) {
		//clark--goodsMapper.xml 中命名空间name = clark,insertGood---insert id
		int result = sessionFactory.openSession().insert("clark.insertGood", goods);
		//mybatis事物需要手动提交,默认为false
		sessionFactory.openSession().commit();
		return result;
	}
	@Override
	public int updateGoods(Goods goods) {
		int result = sessionFactory.openSession().update("clark.updateGood", goods);
		//mybatis事物需要手动提交,默认为false
		sessionFactory.openSession().commit();
		return result;
	}
	@Override
	public int deleteGoods(Integer id) {
		int result = sessionFactory.openSession().delete("clark.deleteGood", id);
		//mybatis事物需要手动提交,默认为false
		sessionFactory.openSession().commit();
		return result;
	}
	@Override
	public Goods findGoodById(Integer id) {
		Goods goods = sessionFactory.openSession().selectOne("clark.selectGoodById",id);
		return goods;
	}
	@Override
	public List<Goods> findAllGoods() {
		List<Goods> gg = sessionFactory.openSession().selectList("clark.selectAllGoods");
		return gg;
	}
	@Override
	public List<Goods> findGoodsByPage(Map<String, PageBean> map) {
		List<Goods> gg = sessionFactory.openSession().selectList("clark.selectGoodsByPage",map);
		return gg;
	}
}
GoodsService.java
package com.clark.service;

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

import com.clark.model.Goods;
import com.clark.util.PageBean;

public interface GoodsService {
	public int insertGoods(Goods goods);
	
	public int updateGoods(Goods goods);
	
	public int deleteGoods(Integer id);
	
	public Goods findGoodById(Integer id);
	//find all
	public List<Goods> findAllGoods();
	
	public List<Goods> findGoodsByPage(Map<String,PageBean> map);	
}
GoodsServiceImpl.java
package com.clark.service.impl;

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

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

import com.clark.dao.GoodsDao;
import com.clark.model.Goods;
import com.clark.service.GoodsService;
import com.clark.util.PageBean;
@Service
public class GoodsServiceImpl implements GoodsService{
	@Autowired
	private GoodsDao goodsDao;
	@Override
	public int insertGoods(Goods goods) {
		return goodsDao.insertGoods(goods);
	}
	@Override
	public int updateGoods(Goods goods) {
		return goodsDao.updateGoods(goods);
	}
	@Override
	public int deleteGoods(Integer id) {
		return goodsDao.deleteGoods(id);
	}
	@Override
	public Goods findGoodById(Integer id) {
		return goodsDao.findGoodById(id);
	}
	@Override
	public List<Goods> findAllGoods() {
		return goodsDao.findAllGoods();
	}
	@Override
	public List<Goods> findGoodsByPage(Map<String, PageBean> map) {
		return goodsDao.findGoodsByPage(map);
	}

}
单元测试类如下:
package maven;

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

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.clark.model.Goods;
import com.clark.service.GoodsService;
import com.clark.util.PageBean;

public class GoodsTest {
	private GoodsService goodsService;
    
    @Before
    public void before(){                                                                   
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"
                ,"classpath:spring-mybatis.xml"});
        //注意此处的beanName 必须与XXXXServiceImpl implements XXXXService的名字相同,而且第一个字母必须小写,否则找不到bean
        goodsService = (GoodsService) context.getBean("goodsServiceImpl");
    }
    @Test
    public void testFindGoodsById(){
        Goods goods = goodsService.findGoodById(18);
        System.out.println(goods.toString());
    }
    @Test
    public void testFindAllGoods(){
        List<Goods> goods = goodsService.findAllGoods();
        for (Goods goods2 : goods) {
        	System.out.println(goods2.toString());
		}
    }
    @Test
    public void testFindGoodsByPage(){
    	PageBean pageBean = new PageBean(8,20);
    	Map<String,PageBean> map = new HashMap<String,PageBean>();
    	map.put("pageBean", pageBean);
        List<Goods> goods = goodsService.findGoodsByPage(map);
        for (Goods goods2 : goods) {
        	System.out.println(goods2.toString());
		}
    }
    @Test
    public void testAddGoods(){
        Goods user = new Goods(20, 23, "oooo", 23.03, "this is one", 5, new Date());
        System.out.println("111111111");
        System.out.println(goodsService.insertGoods(user));
    }
    @Test
    public void testUpdateGoods(){
    	Goods goods = goodsService.findGoodById(18);
    	goods.setName("AOAO");
    	goods.setOrderNo(26);
    	System.out.println(goodsService.updateGoods(goods));
    }
    
}
接着将Mybatis集成SpringMVC中,部署成网页版的小功能实现:
spring-mvc.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<beans 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.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
	<mvc:annotation-driven/>
	<!-- 扫描组件controller -->
	<context:component-scan base-package="com.clark.controller" />
	<!-- 配置模型视图添加前后缀 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/jsp/" p:suffix=".jsp" />
</beans>
web.xml配置如下
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <!-- 读取spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml;
            classpath:spring-mybatis.xml
        </param-value>
    </context-param>
    <!-- 设计路径变量值 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
 
 
    <!-- Spring字符集过滤器 -->
    <filter>
        <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- springMVC核心配置 -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
 
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <!-- 错误跳转页面 -->
    <error-page>
        <!-- 路径不正确 -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
</web-app>
简单的Controller类如下:
package com.clark.controller;

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

@Controller
@RequestMapping("/")
public class GoodsController {
	@RequestMapping("index")
    public String index(){
        return "index";
    }
}
执行相应的打包操作:maven-install 生成war包部署成功之后:
地址栏输入http://localhost:8080/maven/index.do
页面出现===========

Spring MVC 成功

说明成功完成整合。















MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)