mybatis筆記1 基本的配置和操做

mybatis比較輕量,適合開發比較小型的或者業務比較複雜的系統;java

相對於hibernate來講能夠靈活的寫sql,更靈活的處理遇到的業務邏輯;mysql

能夠說hibernate是pojo實體對db的orm映射,而mybatis是pojo對sql的映射;程序員

做爲入門,先不考慮高級的特性,速度來一個CRUD再從源碼和一個具體的業務來研究它的原理和高級特性;web

 

CRUD基本思路:做爲一種比較流行的持久層ORM框架,至關於三層架構中的dao層;spring

最終做爲程序員的咱們使用的SqlSession對象,先來個思路,再來個實現,最後研究細節;sql

image

 

環境準備,結合springmvc,作一個對博客文章的crud,下面貼出配置文件先;express

第一列是依賴文件,都是在倉庫中找到的最新的來用,兼容性如何暫且無論,先把簡單的例子弄出來是關鍵;apache

第二列是web.xml的配置文件,定義一個spring的容器和mvc的url代理servlet;api

第三列纔是mybatis的使用環境準備,結合上圖,上下往上推導定義出SqlSessionFactory,再定義出datasource和mapper配置文件;session

第四列是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先來,這是概要;

image

而後是url映射:

image

servic直接略過,主要關注dao的實現,先來個接口先;

image

 

實現:

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,那會更簡單,有空我改爲註解的,敬請期待…

來幾張效果圖先:

image

 

image

 

兩個圖對比標識完成了分頁的操做;

image

image

兩個圖對比表示實現了增長的功能;

 

image

image

兩個圖對比表示實現了編輯的功能;

 

image

最後標識實現了刪除的功能;

 

到這裏crud的程序算完成了,mybatis成功的入門了…

 

對了,附上源碼...

相關文章
相關標籤/搜索