spring+springMVC+ibatis集成示例

搭建spring + spring MVC + ibatis

前提條件:

(一)       安裝數據庫,此代碼例子使用oracle;若是其它數據庫,修改applicationContext-core.xml文件中jdbc驅動和url連接即可;


(二)       新建表AA,表結構


Sql語句:

CREATETABLE "AA"
   ( "NAME"VARCHAR2(200),
         "SEX" NUMBER,
         "AGE" VARCHAR2(50),
         "ID" VARCHAR2(100),
         "PASSWORD" VARCHAR2(100)
  )

 

1.      新建項目springGyc


2.      準備好項目所需的jar包,導入到此項目中

3.      修改web.xml文件,加入ContextLoaderListener(初始化上下文)、DispatcherServlet(初始化Mvc上下文)

內容如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<!-- Spring配置 -->
 	<listener> 
	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
	</listener> 
	   
	  
	<!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
	<context-param> 
	  <param-name>contextConfigLocation</param-name> 
	  <param-value>classpath:applicationContext-core.xml</param-value> 
	</context-param>
	
	<!-- Spring MVC配置 -->
	<!-- ====================================== -->
	<servlet> 
	  <servlet-name>spring</servlet-name> 
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
	  <!-- 可以自定義servlet.xml配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml 
	  <init-param> 
	    <param-name>contextConfigLocation</param-name> 
	    <param-value>/WEB-INF/spring-servlet.xml</param-value> 默認 
	  </init-param> 
	  -->
	  <load-on-startup>0</load-on-startup> 
	</servlet> 
	  
	<servlet-mapping> 
	  <servlet-name>spring</servlet-name> 
	  <url-pattern>*.do</url-pattern> 
	</servlet-mapping> 
</web-app>



4.      開發spring Mvc配置,spring-servlet.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: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-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">
	<!-- 自動掃描,完成bean創建和依賴注入 --> 
	<!-- 用了context:component-scan標籤,context:annotation-config標籤就可以不用了
	<context:annotation-config /> 
	 -->
	<context:component-scan base-package="com.gyc.dmz.rest"/> 
	     
	<!-- 視圖解析器 --> 
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>  
    
</beans>


5.      applicationContext-core.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: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-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">

	<context:component-scan base-package="com.gyc" />

	<tx:annotation-driven transaction-manager="txManager" />

	<!-- 數據源的Bean事務管理器 -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url">
			<value>jdbc:oracle:thin:@127.0.0.1:1526:mydb</value>
		</property>
		<property name="username">
			<value>gyc</value>
		</property>
		<property name="password">
			<value>123456</value>
		</property>
		<property name="driverClassName">
			<value>oracle.jdbc.driver.OracleDriver</value>
		</property>
	</bean>

	<!-- ibatis的工廠數據源配置1 -->
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="classpath:sqlMap_config.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!--根據sqlMapClien創建一個SqlMapClient模版類 -->
	<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>

</beans>


6.      sqlMap_config.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>
	<settings useStatementNamespaces="true" maxRequests="3000" maxSessions="1000" maxTransactions="3000" />
    <sqlMap resource="com/gyc/biz/dmz/dao/sql/AA_SqlMap.xml"/>
</sqlMapConfig>


7.      開發AA表的業務代碼,dao和Services層代碼

使用Generator MyBatis/iBatis Artifacts插件自動生成代碼(參考之前的博客);

8.      開發controller層,AaRest.java

代碼如下:

/**
 * 
 */
package com.gyc.dmz.rest;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gyc.biz.dmz.dto.Aa;
import com.gyc.biz.dmz.services.AaServices;

/**
 * @ClassName: AaRest
 * @Description: TODO(這裏用一句話描述這個類的作用)
 * @author EX-GEYOUCHAO001
 * @date 2015年11月24日 下午3:20:04
 * 
 */
@Controller
@RequestMapping("aa")
public class AaRest {

	@Autowired
	private AaServices aaServices;
	private Aa aa = null;

	@RequestMapping("queryAaById")
	public String queryAaById(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("geyc--------queryAaById-----");
		String id = request.getParameter("id");
		System.out.println("geyc--------id:-----" + id);
		aa = aaServices.selectByPrimaryKey(id);
		if (aa != null){
			request.setAttribute("aa", aa);
		}
		return "aa";
	}

	@RequestMapping("queryAaMapById")
	public Map<String, Object> queryAaMapById(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		System.out.println("geyc--------queryAaById-----");
		String id = request.getParameter("id");

		System.out.println("geyc--------id:-----" + id);
		aa = aaServices.selectByPrimaryKey(id);
		result.put("aa", aa);
		return result;
	}

	@RequestMapping("addAa")
	// 測試url:http://localhost:7001/springgyc/aa/addAa.do?id=2001&name=zhaoyun&sex=1&age=20
	public String addAa(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("geyc--------addAa-----");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String age = request.getParameter("age");

		Aa aa = new Aa();
		aa.setId(id);
		aa.setName(name);
		aa.setAge(age);
		aa.setSex(new BigDecimal(sex));
		this.aaServices.insert(aa);
		request.setAttribute("aa", aa);

		return "aa";
	}

	@RequestMapping("updateAa")
	public String updateAa(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("geyc--------updateAa-----");
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String age = request.getParameter("age");

		Aa aa = new Aa();
		aa.setId(id);
		if (StringUtils.isNotEmpty(name)){
			aa.setName(name);
		}
		if (StringUtils.isNotEmpty(age)){
			aa.setAge(age);
		}
		if (StringUtils.isNotEmpty(sex)){
			aa.setSex(new BigDecimal(sex));
		}
		this.aaServices.updateByPrimaryKeySelective(aa);
		request.setAttribute("aa", aa);

		return "aa";
	}

	@RequestMapping("deleteAa")
	public String deleteAa(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("geyc--------deleteAa-----");
		String id = request.getParameter("id");
		Aa aa = aaServices.selectByPrimaryKey(id);

		this.aaServices.deleteByPrimaryKey(id);

		request.setAttribute("aa", aa);
		return "aa";
	}

	public Aa getAa() {
		return aa;
	}

	public void setAa(Aa aa) {
		this.aa = aa;
	}

}


9.      啓動應用服務器,如tomcat,可以在瀏覽器中測試我們寫的接口了。

如:添加一條數據

http://localhost:7001/springgyc/aa/addAa.do?id=2001&name=zhaoyun&sex=1&age=20

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章