spring3和mybatis3的初始探索

      终于打算踏踏实实开始写我的技术博客了,也算是对前进道路的总结。

      前阵子看了看mybatis3,之前的项目一直用ibatis2,不料想,技术发展的如此迅猛,已经到mybatis3了。

 

      谈谈mybatis3与ibatis2的不同处:

      1.更加自动化,但同时也降低了灵活度。mybatis将原有dao层全部变成interface,自动与mapping映射文件绑定,不需要再单独在配置文件中一一指定对应关系,这点可能是目前体会到与ibatis2最大的不同。

      2.mapping映射文件中dtd做了很大的更改,原有的很多标签都不能识别,名称全部更新。

      3.原有的sqlmap命名方式全部改成了sqlsession,这点倒是和hibernate有点像了。

 

      一个简单的与spring3结合的小程序,前后台已经运行通。

      1.pojo层

public class CityObj implements java.io.Serializable {
	private static final long serialVersionUID = 5454155825314635342L;
	
	//alias
	public static final String TABLE_ALIAS = "City";
	public static final String ALIAS_CITYID = "cityid";
	public static final String ALIAS_CITYNAME = "cityname";
	public static final String ALIAS_PROID = "proid";
	
	//date formats
	
	//columns START
	private java.lang.Integer cityid;
	private java.lang.String cityname;
	private java.lang.Integer proid;
	//columns END


	public void setCityid(java.lang.Integer value) {
		this.cityid = value;
	}

	public java.lang.Integer getCityid() {
		return this.cityid;
	}
	public void setCityname(java.lang.String value) {
		this.cityname = value;
	}

	public java.lang.String getCityname() {
		return this.cityname;
	}
	public void setProid(java.lang.Integer value) {
		this.proid = value;
	}

	public java.lang.Integer getProid() {
		return this.proid;
	}


	public String toString() {
		final StringBuilder sb = new StringBuilder();
        sb.append("ProvinceObj");
        sb.append("{Cityid='").append(cityid).append('\'');
        sb.append("{Cityname='").append(cityname).append('\'');
        sb.append("{Proid='").append(proid).append('\'');
        sb.append('}');
        return sb.toString();
		
	}
	
	
}
 

 2.dao层接口文件

public interface CityMapper {
	
	CityObj queryById(CityObj cObj);
	
	int insertByObj(CityObj cObj);

}

 映射文件

<?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="org.mybatis.jpetstore.persistence.CityMapper">

  <cache />
  
  <!-- 用于select查询公用抽取的列 -->
	<sql id="cityColumns">
	    <![CDATA[
        cityid ,cityname ,proid 
	    ]]>
	</sql>

  <select id="queryById" resultType="CityObj">
    SELECT <include refid="cityColumns"/>
	    <![CDATA[
	        FROM city
	        limit 1
	    ]]>
  </select>

 <insert id="insertByObj" useGeneratedKeys="true" keyProperty="cityid">
    <![CDATA[
        INSERT INTO city (
        	cityname ,
        	proid 
        ) VALUES (
        	#{cityname} ,
        	#{proid} 
        )
    ]]>
  
 </insert>
 
  

</mapper>

 3.service层

@Service
public class CityService {
	
	@Autowired
	private CityMapper cityMapper;
	
	public CityObj queryById(CityObj cObj){
		return cityMapper.queryById(cObj);
	}
	
	public int insertByObj(CityObj cObj){
		return cityMapper.insertByObj(cObj);
	}

}

 4.web层

@Controller
@RequestMapping(value = "/city")
public class CityController{
	@Autowired
	private CityService cityService;
	
	private final String LIST_ACTION = "redirect:/city/list.do";
	
	public CityController() {
	}
	
	/** 
	 * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写
	 **/
	public void setCityService(CityService Service) {
		this.cityService = Service;
	}

	/**
	 * 增加了@ModelAttribute的方法可以在本controller的方法调用前执行,可以存放一些共享变量,如枚举值
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}
	
	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "/show.do", method = RequestMethod.GET)
	public ModelAndView show(HttpServletRequest request,HttpServletResponse response) throws Exception {
		CityObj cityObj = new CityObj();
		cityObj.setCityid(1);
		CityObj city = cityService.queryById(cityObj);
		System.out.println("***************");
		System.out.println(city);
		return new ModelAndView("/city/show","city",city);
	}
	
	@RequestMapping(value = "/insert.do", method = RequestMethod.GET)
	public ModelAndView insert()throws Exception{
		CityObj cityObj = new CityObj();
		cityObj.setCityname("test");
		cityObj.setProid(2);
		int flag = cityService.insertByObj(cityObj);
		System.out.println("***************");
		System.out.println(flag);
		return null;
		
	}


}

 5.3个配置文件

 

application-contxt.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2010 The myBatis Team

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<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"
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.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/umpdb05?useUnicode=true&amp;characterEncoding=GBK"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    
    <!-- transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- enable component scanning (beware that this does not enable mapper scanning!) -->    
    <context:component-scan base-package="org.mybatis.jpetstore.service" />

    <!-- enable autowire -->
    <context:annotation-config />

    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven />

    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="org.mybatis.jpetstore.domain" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.mybatis.jpetstore.persistence" />
    </bean>
</beans>

 sample-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"-->
<!--"http://www.springframework.org/dtd/spring-beans-2.0.dtd">-->
<beans 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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
       default-autowire="byName">
    <!-- maps request URLs to Controller names -->
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <!-- this bean with the well known name generates view names for us -->
    <!-- not strictly required since we just want to accept the defaults-->
    <bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator">
        <property name="alwaysUseFullPath" value="true"/>
    </bean>

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <!--use for resolve the special view eg:htmlReport,excel,pdf -->
    <bean id="beanResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
        <property name="contentType" value="text/html; charset=gbk"/>
    </bean>
    <!--
		- We specify here that Locale and theme are stored in cookies.
	  - They could be stored in a Session. Default resolvers don't allow changing them on the fly.
		-->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
    <bean id="themeResolver" class="org.springframework.web.servlet.theme.SessionThemeResolver">
        <property name="defaultThemeName" value="theme"/>
    </bean>


    <!--扫描注解方式的controller-->
    <context:component-scan base-package="org.mybatis.jpetstore.web.controller"/>

   
</beans>

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	
	<filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GBK</param-value>
        </init-param>
    </filter>
    <!--Encoding Filter Mapping Start-->
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
     <servlet>
        <servlet-name>sample</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>sample</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
</web-app>

 没有写前台jsp,这只是一个最基本的前后台,流程可以跑通,启动后,在浏览器输入:

http://localhost:8400/mybatis-spring-sample/city/show.do

就可以看到控制台的输出信息:

***************
ProvinceObj{Cityid='1'{Cityname='北京市'{Proid='1'}

 说明查询成功,这段信息是放到web层调用输出的。

总的来说,mybatis3的基本使用上与原有的ibatis2差别不大,其他的就要等深入学习后才知道了...

代码我放到附件中了

 

你可能感兴趣的:(Mybatis3)