【Java学习20170524】MyBatis

本文介绍如何将MyBatis与Spring框架整合,并通过具体示例演示了配置过程及基本CRUD操作的实现方法。
MyBatis
1、   配置
1)、配置连接池
2)、创建连接工厂并注入
3)、配置事务的驱动
4)、声明连接方法所在的位置

2、MyBatis的配置文件
1、设置myBatis使用时的相关配置
2、设置连接数据库的执行文件

为了能加载MyBatis和Spring配置文件
1、在SpringMVC配置文件中引用MyBatis和Spring配置文件

2、设置加载springMVC配置文件时,设置同时加载所有文件      --- 【文件的命名受限】


MySpringIbatis

配置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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">


	<!-- 配置哪些类的方法需要进行事务管理 -->
	<bean id="DaoImp" class="com.share.dao.DaoImp">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="sqlMapClient">
			<ref bean="sqlMapClient" />
		</property>
	</bean>

	<!-- 我们需要一个事务管理器,对事务进行管理,实现整合iBatis和Spring的第二步。 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value>123</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://localhost:3306/test</value>
		</property>
	</bean>

	<!-- 我们需要让spring来管理SqlMapClient对象,实现整合iBatis和Spring的第三步 -->
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<!-- 此处应注入ibatis配置文件,而非sqlMap文件,否则会出现“there is no statement.....异常” -->
		<property name="configLocation">
			<value>sqlMapConfig.xml</value>
		</property>
	</bean>



</beans>  
配置sqlMapconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig   
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"   
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">   
<sqlMapConfig>   
  
<sqlMap resource="Ibatis.xml" />   
  
</sqlMapConfig>  

配置ibatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >  
<sqlMap >  

  <typeAlias type="com.share.bean.Ibatis" alias="user"/>  
  
  <resultMap id="ibatisTest" class="user" >  
    <result column="id" property="id" jdbcType="VARCHAR" />  
    <result column="name" property="name" jdbcType="VARCHAR" />  
  </resultMap>  
    
  <!-- 获得全查询列表 -->  
  <select id="getAllUsers" resultMap="ibatisTest">  
    select * from ibatis  
  </select>  
    
   <!-- 根据用户名获得用户对象 -->  
   <select id="getUsersByName" resultMap="ibatisTest">  
     select * from ibatis where name=#value#  
  </select>   
    
  <!-- 根据id获得用户对象 -->  
    <select id="getUsersById" resultMap="ibatisTest">  
     select * from ibatis where id=#value#  
  </select>   
    
   <!-- 新增用户对象 -->  
   <insert id="insertUsers" parameterClass="user">  
      insert into ibatis (id,name) values (#id#,#name#)  
   </insert>  
     
   <!-- 删除用户对象 -->  
   <delete id="deleteUsers">  
     delete from ibatis where id=#value#  
   </delete>  
     
   <!-- 更新用户对象 -->  
   <update id="updateUsers" parameterClass="user">  
      update ibatis set name=#name# where id=#id#  
   </update>  
</sqlMap>  

bean

package com.share.bean;

public class Ibatis {

	private String id;
	private String name;

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Ibatis() {

	}

	public Ibatis(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}
dao

package com.share.dao;

import java.util.List;

import com.share.bean.Ibatis;

public interface Dao {
	/**获取全部的数据*/
	public List<Ibatis> getList();
	/**根据name查询数据*/
	public Ibatis getByName(String name);
	/**根据id查询数据*/
	public Ibatis getById(String id);
	/**插入数据*/
	public void insert(Ibatis ibatis);
	/**删除数据*/
	public void delete(String id);
	/**更新*/
	public void update(Ibatis ibatis);
}

package com.share.dao;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.share.bean.Ibatis;

public class DaoImp extends SqlMapClientDaoSupport implements Dao {  
	  
    public void delete(String id) {  
        getSqlMapClientTemplate().delete("deleteUsers", id);  
    }  
  
    public Ibatis getById(String id) {  
        return (Ibatis)getSqlMapClientTemplate().queryForObject("getUsersById",id);  
    }  
  
    public Ibatis getByName(String name) {  
          
        return (Ibatis)getSqlMapClientTemplate().queryForObject("getUsersByName",name);  
    }  
  
    @SuppressWarnings("unchecked")  
    public List<Ibatis> getList() {  
        return getSqlMapClientTemplate().queryForList("getAllUsers",null);  
    }  
  
    public void insert(Ibatis ibatis) {  
        getSqlMapClientTemplate().insert("insertUsers",ibatis);  
    }  
  
    public void update(Ibatis ibatis) {  
        getSqlMapClientTemplate().update("updateUsers", ibatis);  
    }  
  
}  
test

package com.share.test;

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.share.bean.Ibatis;
import com.share.dao.DaoImp;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		DaoImp dao = (DaoImp) context.getBean("DaoImp");
		 dao.insert(new Ibatis("100001","tangx"));
//		 Ibatis ibatis3 = dao.getById("4");
//		 ibatis3.setName("tangxin");
//		 dao.update(ibatis3);
//		 dao.delete("4");
		System.out.println("获得全查询列表");
		List<Ibatis> result = new ArrayList<Ibatis>();
		result = dao.getList();
		for (Iterator<Ibatis> iter = result.iterator(); iter.hasNext();) {
			Ibatis element = (Ibatis) iter.next();
			System.out.println(element.getName());
		}
	}

}


SpringMVC_MyBatis_One


配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringMVC_MyBatis_One</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>Dispatcher</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:application.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>Dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping> 
  
</web-app>


配置application.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

	<!-- 配置连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/mysql" />
		<property name="username" value="root" />
		<property name="password" value="123" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="5"></property>
		<!-- 连接池最大数量 -->
		<property name="maxActive" value="25"></property>
		<!-- 连接池最大空闲 -->
		<property name="maxIdle" value="25"></property>
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="5"></property>
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="60000"></property>
	</bean>

	<bean id="Tangxin" class="com.share.dao.DaoImpl">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="sqlMapClient">
			<ref bean="sqlMapClient" />
		</property>
	</bean>

	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<!-- 此处应注入ibatis配置文件,而非sqlMap文件,否则会出现“there is no statement.....异常” -->
		<property name="configLocation">
			<value>classpath:com/share/ibatis/MySqlMapConfig.xml</value>
		</property>
	</bean>




	<bean id="upController" class="com.share.controller.UpController">
		<property name="successView" value="user_info"></property>
		<property name="failView" value="user_info"></property>
	</bean>

	<bean id="nextController" class="com.share.controller.NextController">
		<property name="ok" value="user_info"></property>
		<property name="no" value="user_info"></property>
	</bean>

	<bean id="urlMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/up.do">upController</prop>
				<prop key="/next.do">nextController</prop>
			</props>
		</property>
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>
配置MySqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
  
  <sqlMap resource="com/share/ibatis/Tx.xml"/>
</sqlMapConfig>
配置Tx.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap >
  <typeAlias alias="tx" type="com.share.user.User"/> <!-- 声明一个类作为结果的类,给这个类取一个别名 -->
  
  <resultMap id="txtest" class="tx">  <!-- 设置返回结果集格式   给这个结果集取一个别名:txtest, 引用结果类-->
    <result property="name" column="username" jdbcType="VARCHAR"/>
    <result property="pwd" column="userpassword" jdbcType="VARCHAR"/>
  </resultMap>
  
  <!-- 获得全查询列表 -->  
  <select id="uppage" resultMap="txtest" parameterClass="com.share.user.MyData">  
    select * from user_tab limit #current_page#,#size#
  </select>  
  
  <!-- 新增用户对象 -->  
   <select id="nextpage" parameterClass="com.share.user.MyData" resultMap="txtest">  
      select * from user_tab limit #current_page#,#size#
   </select>  
</sqlMap> 




controller

package com.share.controller;

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

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.share.dao.Dao;
import com.share.user.MyData;
import com.share.user.User;



public class UpController extends AbstractController {
	private String successView;
	private String failView;
	
	public String getSuccessView() {
		return successView;
	}
	public void setSuccessView(String successView) {
		this.successView = successView;
	}
	public String getFailView() {
		return failView;
	}
	public void setFailView(String failView) {
		this.failView = failView;
	}
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		 ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");  
         Dao dao = (Dao)context.getBean("Tangxin");  
         
		System.out.println("ok?");
		int current=Integer.parseInt(request.getParameter("current"));
		int size=Integer.parseInt(request.getParameter("size"));
		System.out.println(current+"     "+size);
		List<User> list=dao.Up(new MyData(current,size));
		Map<String ,Object> model=new HashMap<String,Object>();
		if(list!=null){
			model.put("success", list);
		}else{
			model.put("error", "用户名或密码错误");
		}
		return new ModelAndView(getSuccessView(),model);	
	}
	

}

package com.share.controller;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class NextController extends AbstractController{
	
	private String ok;
	private String no;

	
	
	public String getOk() {
		return ok;
	}



	public void setOk(String ok) {
		this.ok = ok;
	}



	public String getNo() {
		return no;
	}



	public void setNo(String no) {
		this.no = no;
	}



	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}

dao

package com.share.dao;

import java.util.List;

import com.share.user.MyData;
import com.share.user.User;

public interface Dao {

		public List<User> Up(MyData data);
		
		public List<User> next(MyData data);
	
}

package com.share.dao;

import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.share.user.MyData;
import com.share.user.User;


public class DaoImpl extends SqlMapClientDaoSupport implements Dao{

	@SuppressWarnings("unchecked")
	@Override
	public List<User> Up(MyData data) {
		// TODO Auto-generated method stub
		return getSqlMapClientTemplate().queryForList("uppage",data); 	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> next(MyData data) {
		// TODO Auto-generated method stub
		return getSqlMapClientTemplate().queryForList("nextpage",data);
	}

	

}
user

package com.share.user;

public class User {
	public String name;
	public String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

package com.share.user;

public class MyData {
	private int current_page;
	private int size;

	public int getCurrent_page() {
		return current_page;
	}

	public void setCurrent_page(int current_page) {
		this.current_page = current_page;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public MyData() {
	}

	public MyData(int current_page, int size) {
		this.current_page = current_page;
		this.size = size;
	}

}
<%@ 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>
	<jsp:forward page="up.do?current=0&size=4"></jsp:forward>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
<script type="text/javascript" src="js/jquery-3.0.0.min.js"></script>
<script type="text/javascript">

</script>


<title>Insert title here</title>
</head>
<body>
	<table border="1" id="tab">
		<tr>
			<td>用户名</td> <td>密码</td>
		</tr>
		<tr>
			<td id="name"></td>
			<td id="pwd"></td>
		<tr/>
			<c:forEach items="${success}" var="user">
				<tr>
					<td>
						${user.name }
					</td>
					<td>
						${user.pwd }
					</td>
				</tr>
			</c:forEach>
		<tr id="footer">
			<td><a href="up.do?current=0&size=4" class="pre">上一页</a></td>
			<td><a href="up.do?current=4&size=4" class="next">下一页</a></td>
		</tr>
	</table>
	<div id="dd"></div>
</body>
</html>


<%@ 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>
	${error}
</body>
</html>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值