MyBatis+SpringMVC+SpringBootJava开发那些事Java学习笔记

Mybatis入门教程

2017-06-16  本文已影响422人  Real_man

简介

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。[1]

本文将演示Mybatis的基本用法,通过XML或接口类对数据库的增删改查。

创建Mybatis项目

1、使用Idea创建一个maven项目,依赖包内容如下


    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
    </dependencies>

2、创建Mybatis配置文件
使用Idea集成开发环境,可以下载Mybatis plugin,然后可更好的使用mybatis。关于mybatis的破解过程,参考附录的mybatis plugin 破解

新建Mybatis配置文件

项目文件内容

1、在resource目录下增加mybatis-config.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>

    <properties>
        <property name="jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="jdbc.user" value="aihe" />
        <property name="jdbc.pass" value="123456" />
        <property name="jdbc.url" value="jdbc:mysql://localhost:3306/test" />
    </properties>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <!--便于后面解析对象-->
    <typeAliases>
        <package name="me.aihe" />
    </typeAliases>
    <!-- Continue going here -->
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.user}" />
                <property name="password" value="${jdbc.pass}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="BlogMapper.xml" />
    </mappers>

</configuration>

2、在resource目录下增加BlogMapper.xml文件,内容如下

<?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="me.aihe.dao.BlogMapper">

    <select id="selectBlog" resultType="me.aihe.Blog">
        select * from Blog where id = #{id}
    </select>

    <insert id="insertBlog" parameterType="Blog">
        insert into Blog (id,title) values (#{id},#{title})
    </insert>

    <update id="updateBlog" parameterType="Blog">
        UPDATE Blog SET title=#{title} WHERE id=#{id}
    </update>

    <delete id="deleteBlog" parameterType="integer">
        DELETE FROM BLOG WHERE id=#{id}
    </delete>

</mapper>

3、新建Blog对象

package me.aihe;

public class Blog {
    int id;
    String title;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", title='" + title + '\'' +
                '}';
    }
}

4、新建主文件,Tutorial.java,并进行测试。
当前我们的数据表内容如下

新建数据表

5、Tutorial.java文件内容如下

package me.aihe;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class Tutorial {
    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 查询数据库内容
            sqlSession = sqlSessionFactory.openSession();
            Blog blog = sqlSession.selectOne("me.aihe.dao.BlogMapper.selectBlog",1);
            System.out.println(blog);

            // 插入数据库内容
            Blog b = new Blog();
            b.setTitle("Insert Value" + new Random().nextInt(1000));
            int row = sqlSession.insert("me.aihe.dao.BlogMapper.insertBlog",b);
            System.out.println(row);
            sqlSession.commit();

            // 更新数据库内容
            b.setId(2);
            row = sqlSession.update("me.aihe.dao.BlogMapper.updateBlog",b);
            System.out.println(row);
            sqlSession.commit();


            //删除数据库内容
            row = sqlSession.delete("me.aihe.dao.BlogMapper.deleteBlog",1);
            System.out.println(row);
            sqlSession.commit();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

}

最终的项目结构如下

项目结构

6、运行结果

Blog{id=1, title='Hello Mybatis'}
1
1
1

查看当前数据表的内容,可见查询了id为1的数据,插入了一条心的数据,更新了id为2 的数据,删除了id为1的数据。

演示后数据表内容

总结

这篇文章主要简单的演示了通过xml配置Mybatis,对数据库的增删改查。使用接口注解的方式类似,可自行查阅。关于更多高级用法,请听下回分解。

可扩充部分

错误汇总

1、mybatis-config.xml属性顺序错误

Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 50; columnNumber: 17; 元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"

解决方案:mybatis-config.xml文件按照(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)进行顺序排列。

mybatis配置顺序

2、不能找到某个类文件

Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in BlogMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Blog'.  Cause: java.lang.ClassNotFoundException: Cannot find class: Blog

解决方案:两者选其一即可
1、在Mapper文件的resultType中返回为全路径

解决方案1

2、添加TypeAlias

解决方案2

附录

上一篇下一篇

猜你喜欢

热点阅读