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&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差别不大,其他的就要等深入学习后才知道了...
代码我放到附件中了
- mybatis-spring-sample.rar (6.8 MB)
- 下载次数: 25
相关推荐
ssb(struts2,spring3,mybatis3)实现的家庭费用记录系统,页面已经做好,思路是根据本人实际情况定制:总支出与总收入不计算信用卡、每月记录消费时需先记录本月原有金额等。 功能包括:本月当天支出于收入、本月总支...
Maven3+spring3+mybatis3+dwr3+mysql5.5,请用Chrome浏览器,兼容性还未调试。 自己写的一个小系统,包含一个模块:产品模块。 基本这个模块包括的内容就比较多了,CRUD,无刷新查询,图片上传等, 其实也是整个...
这是一个用Eclipse4所做的一个基于Spring3.2和Mybatis3.2所做的一个整合的Demo,包括初始化数据脚本,但不包括jar包
具体包括添加H2数据库依赖、配置Spring Boot的数据源连接信息、对Mybatis进行基本设置,以及如何初始化和操作数据库。 适用人群:该教程适合已具备基础Java和Spring Boot开发经验的开发者,尤其是需要快速构建轻量...
这是一个用Eclipse4所做的基于struts2.3、spring3.2和mybatis3.2整合的Demo,Demo中包含了详细的配置说明和初始化脚本,但不包括jar包,所以,如果需要请联系我,QQ:156296788
OSGI企业应用开发(十五)基于Spring、Mybatis、Spring MVC实现一个登录应用博文源码
包含mySQL数据库初始化脚本,包含spring+spring web MVC+mybatis的整合,包含mabatis-generator这个插件的使用以及配置,整个工程可以正常运行。
spring+mvc+mybatis+mysql+jsp 实现用户登录、注册功能 进入系统,实现用户的查询、修改、删除、更新 导入项目,请修改数据库配置文件,运行创建表并插入数据 初始登录用户名:admin1 密码:123456
Spring集成SpringMVC/Mybatis,有初始化脚本
手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis 博客地址:http://blog.csdn.net/qq598535550/article/details/51703190 我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能;而且在大...
mybatis实战教程mybatis in action之五与spring3集成附源码 mybatis实战教程mybatis in action之六与Spring MVC 的集成 mybatis实战教程mybatis in action之七实现mybatis分页源码下载 mybatis实战教程mybatis in ...
3、自定义redis KEY生成器/CacheManager来管理redis缓存 4、分布式redis-session共享 5、springboot实现初始化加载配置(实现缓存预热)的两种方式 6、二级缓存联合使用 方式一:redis原生方法工具类(RedisService...
3、水质相关信息 水质相关信息模块以日历框形式,初始以不同颜色显示 “水质达标”与“水质不达标”字样,点击“合格”与“不合格”字样,可以显示余氯、浊度、PH值等数据。 4、现场图片信息 现场图片信息模块以...
本项目集成了springboot+security+mybatis+redis+jwt用于学习security鉴权功能,其中有集成了redis,mybatis,jasypt,jwt,thymeleaf,knife4j,mybatis-plus 项目搭建已经比较成熟,能够直接进行使用,通过代码...
Spring+Mybatis+Atomikos实现JAVA初始化并控制多个数据源+分布式事务的一个DEMO,内涵源代码,以及一篇关于该内容的博客
mybatis+spring+struts必需的jar包一个不多一个不少
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,spring boot 给予html
URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的...