Mybatis

距离上一次看书已经是10天的时间了。。。
体能太差,一锻炼就没精神干别的事。。总想睡觉。。不过没看书总觉得慌。。所以还是要努力克服~~!!
今天继续Mybatis。。因为工作中的项目会用到,网上查到的教程贴又五花八门。。所以还是系统的按一个教程先学一下。。
最近活有点多。。陆陆续续终于看完了。。教程是做了一个项目来讲的。。这里只记录mybatis相关的

————————————————————————————————————————————————————————————

一、引入Mybatis包

maven加入配置

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

二、加入Mybatis配置

这里配置有两种

1、主配置,用于连接数据库,并引入其他表的sql.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com\shane\conf\sqlXml\message.xml"/>
    </mappers>

</configuration>

2、sql.xml配置

配置各个表的sql映射

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

       Copyright 2009-2016 the original author or authors.

       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.

-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

    <resultMap type="com.shane.model.Message" id="MessageResult">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="command" jdbcType="VARCHAR" property="command"/>
        <result column="description" jdbcType="VARCHAR" property="description"/>
        <result column="content" jdbcType="VARCHAR" property="content"/>
    </resultMap>

    <select id="query" parameterType="com.shane.model.Message" resultMap="MessageResult">
        select id,command,description,content from message where 1=1
        <if test="command != null and !&quot;&quot;.equals(command.trim())">
            and command = #{command}
        </if>
        <if test="description != null and !&quot;&quot;.equals(description.trim())">
            and description like '%' #{description} '%'
        </if>
    </select>
    <delete id="deleteOne" parameterType="int">
        DELETE FROM message where id=#{id}
    </delete>
    <delete id="deleteBatch" parameterType="java.util.List">
        DELETE FROM message where id in
        <foreach collection="list" item="item" separator=",">
            #{item}
        </foreach>
    </delete>
    <!--<select id="version" parameterType="long" resultType="int">-->
    <!--SELECT version FROM user WHERE id = #{id,jdbcType=INTEGER}-->
    <!--</select>-->

    <!--<delete id="delete" parameterType="UserAlias">-->
    <!--DELETE FROM user WHERE id = #{id:INTEGER}-->
    <!--</delete>-->

    <!--<insert id="insert" parameterType="UserAlias" useGeneratedKeys="false">-->
    <!--INSERT INTO user-->
    <!--( id,-->
    <!--username,-->
    <!--password,-->
    <!--administrator-->
    <!--)-->
    <!--VALUES-->
    <!--( #{id},-->
    <!--#{username,jdbcType=VARCHAR},-->
    <!--#{password.encrypted:VARCHAR},-->
    <!--#{administrator,jdbcType=BOOLEAN}-->
    <!--)-->
    <!--</insert>-->

    <!--<update id="update" parameterType="UserAlias">-->
    <!--UPDATE user SET-->
    <!--username = #{username,jdbcType=VARCHAR},-->
    <!--password = #{password.encrypted,jdbcType=VARCHAR},-->
    <!--administrator = #{administrator,jdbcType=BOOLEAN}-->
    <!--WHERE-->
    <!--id = #{id,jdbcType=INTEGER}-->
    <!--</update>-->

    <!--&lt;!&ndash;   Unique constraint check &ndash;&gt;-->
    <!--<select id="isUniqueUsername" parameterType="map" resultType="boolean">-->
    <!--SELECT (count(*) = 0)-->
    <!--FROM user-->
    <!--WHERE ((#{userId,jdbcType=BIGINT} IS NOT NULL AND id != #{userId,jdbcType=BIGINT}) OR-->
    <!--#{userId,jdbcType=BIGINT} IS-->
    <!--NULL)  &lt;!&ndash; other than me &ndash;&gt;-->
    <!--AND (username = #{username,jdbcType=VARCHAR})-->
    <!--</select>-->
</mapper>

下面注掉的是demo里面的,上面是教程里面用到的
namespase是用于区分表的,每个表下的语句id不能重复,
不同的语句用不同的标签写,如select、delete等
resultMap类似于表结构映射,映射java中的model类和表的对应字段
sql中的条件拼接用OGNL进行具体使用如下图

三、获取SqlSession

在java中读取mybatis主配置文件,用该配置创建一个SqlSessionFactory,再用Factory创建一个sqlSession,就可以进行sql操作了

public class MyBatisDBUtil {
    public SqlSession getSqlSession() throws IOException {
        //获取配置信息,路径从根目录开始写
        Reader reader = Resources.getResourceAsReader("com/shane/conf/Configuration.xml");
        //通过配置信息构建一个SqlSessionFactory
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(reader);
        //通过SqlSessionFactory获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

四、SQL操作

通过sqlSession进行sql操作

public int deleteOne(int id) {
        SqlSession sqlSession = null;
        MyBatisDBUtil myBatisDBUtil = new MyBatisDBUtil();
        try {
            sqlSession = myBatisDBUtil.getSqlSession();
            sqlSession.delete("Message.deleteOne", id);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return 0;
    }
```![](http://images2015.cnblogs.com/blog/692906/201706/692906-20170627220631977-622767391.png)
![](http://images2015.cnblogs.com/blog/692906/201706/692906-20170627220636899-662320177.png)
posted @ 2017-06-17 18:59  l.shane  阅读(200)  评论(0编辑  收藏  举报