mybatis比较轻量,适合开发比较小型的或者业务比较复杂的系统;
相对于hibernate来说可以灵活的写sql,更灵活的处理遇到的业务逻辑;
可以说hibernate是pojo实体对db的orm映射,而mybatis是pojo对sql的映射;
作为入门,先不考虑高级的特性,速度来一个CRUD再从源码和一个具体的业务来研究它的原理和高级特性;
CRUD基本思路:作为一种比较流行的持久层ORM框架,相当于三层架构中的dao层;
最终作为程序员的我们使用的SqlSession对象,先来个思路,再来个实现,最后研究细节;
环境准备,结合springmvc,做一个对博客文章的crud,下面贴出配置文件先;
第一列是依赖文件,都是在仓库中找到的最新的来用,兼容性如何暂且不管,先把简单的例子弄出来是关键;
第二列是web.xml的配置文件,定义一个spring的容器和mvc的url代理servlet;
第三列才是mybatis的使用环境准备,结合上图,上下往上推导定义出SqlSessionFactory,再定义出datasource和mapper配置文件;
第四列是springmvc的配置文件,相当常见,这里不解释;
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.1.RELEASE</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.1.RELEASE</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.4</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
<!-- 数据源和jdbc驱动依赖 start--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency>
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency>
<!--log4j日志框架--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency>
|
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>mybatis</display-name> <!--spring容器配置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/context-config.xml</param-value> </context-param>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<!--mvc配置--> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/dispatcher-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
</web-app>
|
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.mysql.driverClassName}"/> <property name="url" value="${jdbc.mysql.url}"/> <property name="username" value="${jdbc.mysql.username}"/> <property name="password" value="${jdbc.mysql.password}"/> <property name="maxActive" value="${jdbc.mysql.maxActive}"/> <property name="maxIdle" value="${jdbc.mysql.maxIdle}"/> <property name="initialSize" value="${jdbc.mysql.initialSize}"/> <property name="maxWait" value="${jdbc.mysql.maxWait}"/> </bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
<context:component-scan base-package="com.sz.mybatis.framework.service"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<context:annotation-config />
<tx:annotation-driven />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="singleton" > <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.sz.mybatis.framework.domain.blog" /> <property name="mapperLocations"> <list> <value>classpath:com/sz/mybatis/framework/persist/BlogMapper.xml</value> </list> </property> </bean> <bean id="sqlSession" factory-bean="sqlSessionFactory" factory-method="openSession" scope="prototype"></bean>
|
<context:component-scan base-package="com.sz.mybatis.admin.controller"> <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>--> </context:component-scan> <mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"></property> <property name="prefix" value="/page/"></property> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!--<property name="contentType" value="UTF-8"/>--> </bean>
|
来一个博客对象的增删改查先;controller先来,这是概要;
然后是url映射:
servic直接略过,主要关注dao的实现,先来个接口先;
实现:
package com.sz.mybatis.framework.service.impl;
import com.google.common.collect.ImmutableList; import com.sun.deploy.association.utility.AppConstants; import com.sz.mybatis.framework.domain.Msg; import com.sz.mybatis.framework.domain.PageConfig; import com.sz.mybatis.framework.domain.blog.Blog; import com.sz.mybatis.framework.persist.BlogDao; import com.sz.mybatis.framework.persist.BlogMapper; import com.sz.mybatis.framework.service.BlogService; import com.sz.mybatis.framework.util.SystemConstant; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.List;
/** * Created with IntelliJ IDEA. * User: cutter.li * Date: 14-2-28 * Time: 下午3:07 * 服务实现类 */ @Service public class BlogServiceBean implements BlogService {
@Autowired SqlSession session;
private BlogMapper getBlogMapper() { return session.getMapper(BlogMapper.class); }
@Override public Msg list(PageConfig pageConfig) { if (pageConfig != null) { BlogMapper blogMapper = getBlogMapper(); List<Blog> blogList= blogMapper.list(pageConfig);
Msg msg=new Msg(); if(blogList!=null) { msg.setCode(SystemConstant.SUCCESS); msg.setMessage(SystemConstant.SUCCES_MESSAGE); msg.setData(blogList); } return msg; } return null; }
@Override public Blog listSingle(int id) { if (id > 0) { BlogMapper blogMapper = getBlogMapper(); Blog blog = blogMapper.selectBlog(id); return blog; } return null; }
@Override public void modify(Blog blog) { getBlogMapper().updateBlog(blog); }
@Override public void insert(Blog blog) { getBlogMapper().insertBlog(blog); }
@Override public void remove(int id) { getBlogMapper().deleteBlog(id); } }
|
配置文件:
<?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="com.sz.mybatis.framework.persist.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select>
<select id="list" parameterType="com.sz.mybatis.framework.domain.PageConfig" resultType="com.sz.mybatis.framework.domain.blog.Blog"> select * from Blog order by #{sortField} #{sortOrder} limit #{start},#{pageSize} </select>
<insert id="insertBlog" parameterType="Blog"> insert into Blog (title,contentSummary,contentDetail) values(#{title},#{contentSummary},#{contentDetail}) </insert>
<update id="updateBlog" parameterType="Blog"> update Blog set title=#{title} , contentSummary=#{contentSummary} ,contentDetail=#{contentDetail} where id=#{id} </update>
<delete id="deleteBlog" parameterType="int"> delete from Blog where id=#{id} </delete> </mapper>
|
一个接口方法对应一条配置,通过id对应起来,据说可以在类的注解上面写sql,那会更简单,有空我改成注解的,敬请期待…
来几张效果图先:
两个图对比标识完成了分页的操作;
两个图对比表示实现了增加的功能;
两个图对比表示实现了编辑的功能;
最后标识实现了删除的功能;
到这里crud的程序算完成了,mybatis成功的入门了…
对了,附上源码...