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 成功

说明成功完成整合。

时间: 2024-10-19 15:09:38

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)的相关文章

通过JDBC进行简单的增删改查

通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,简称JDBC)

MongoDB 3.0.6 安装 增删改查

下载 安装包MSI http://yunpan.cn/cmhHdTPkXZRM2  访问密码 9b6c 上边提供的是 MongoDB 3.0.6 64Bit 的安装包 安装 如果不想直接安装在C盘..就要选择自定义安装喽.. 就是选择全部安装和自定义的那一步..全部安装是默认安装C盘的.. 我这里是安装到 D:\Program Files\MongoDB\MongoDB 的.. 需要在 D:\Program Files\MongoDB 下新建 Log 文件夹..并在Log下建立 Log.txt

MyBatis学习--简单的增删改查

jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: 1 Public static void main(String[] args) { 2 Connection connection = null; 3 PreparedStatement preparedStatement = null; 4 ResultSet resultSet = null; 5 6 try { 7 //加载数据库驱动 8 Class.forName

通过JDBC进行简单的增删改查(以MySQL为例) 目录

通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,简称JDBC)

Java通过JDBC进行简单的增删改查(以MySQL为例)

Java通过JDBC进行简单的增删改查(以MySQL为例) 目录: 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作   (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,

myeclipse中JDBC连接mysql和简单的增删改查

废话不多说,直接上操作图,操作起来理解会更彻底 1.myeclipse中项目结构,先在web-inf-lib下导入jar包,注意Web App Libraries这个目录,下面会有用到的地方 2.连接语句 package utils; import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql

通过flask实现web页面简单的增删改查

通过flask实现web页面简单的增删改查 # 1.后台程序falsk_web01.py #coding:utf-8 from flask import Flask,render_template,request,redirect import fileutils # 引入file_dict用户列表 fileutils.file_read() app = Flask(__name__) @app.route('/') def index(): return render_template('lo

使用JDBC分别利用Statement和PreparedStatement来对MySQL数据库进行简单的增删改查以及SQL注入的原理

一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的MySQL Community Server 选择想要的版本进行下载 之后的步骤,因为本人已经安装过MySQL数据库,而卸载重装会比较麻烦,卸载不干净会导致新的装不上,所以可以参考下面的博客,因为官网的改动,前面的部分已经与该博客不符,按照本人在上面的介绍寻找即可 https://blog.csdn

Mybatis使用之简单的增删改查

Mybatis使用之简单的增删改查 一:简介 主要记录最简单的数据的增删改查.下一章会有各个操作详细一点的配置说明.以Author表为例(见上一博客).Author表没有关联任何其他表.也没有特殊字段. 二:映射规则 2.1.映射文件中的sql方法与对应的XxxMapper接口中的方法映射规则: a)映射文件的namespace的值是XxxMapper接口的全限定名.即包名+接口名称 b)映射文件中表示增删改查的标签(select.insert.delete.update)的id的值是接口中方法