Java操作数据库方式五MyBatis使用入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fightingXia/article/details/82082242

##概述

##MyBatis是什么

MyBatis是一个持久层框架,作用是在java项目中操作数据库。

##MyBatis介绍

  1. MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目迁移到了google code,并且改名为MyBatis。 
  2. MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
  3. Mybatis通过xml或注解的方式将要执行的statement配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

下面以项目示例介绍MyBatis框架的使用。

##准备工作

在使用JDBC连接数据库之前,首先要有数据库,数据库要创建表。我的数据库信息如下:

  1. 数据库类型:MySql。
  2. 数据库名字:xia。
  3. 用户名:root。
  4. 密码:root.
  5. 创建数据库表student。
create table student(
       id int primary key auto_increment,
       name varchar(20),
       age int
);

##开发环境

  1. 操作系统:MACOS。
  2. 开发工具:IntelliJ IDEA。
  3. Java版本:jdk1.8。
  4. 使用maven管理jar包。

##正式开发

一,在pom.xml文件中引入需要jar的依赖

    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

二,创建model类

在com.honor.mybatis.model包中创建StudentModel类,字段与student表对应。代码如下:

public class StudentModel {
    private int id;
    private String name;
    private int age;

    //get和set方法略
}

三,创建Mapper文件

在resources/mapper目录下创建student表对应的mapper文件,起名为studentMapper.xml。在该文件中写sql语句,内容如下:

<?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文件的唯一标识,在同一个项目中不能重复-->
<mapper namespace="student">
    <!--插入数据,并返回id。studentModel是在SqlMapConfig.xml文件中定义的别名,也可以写全类名。-->
    <insert id="insert" parameterType="studentModel" useGeneratedKeys="true" keyProperty="id">
        insert into student (name,age)
        values(#{name},#{age})
    </insert>

    <!--根据id查找一条数据-->
    <select id="queryOne" parameterType="int" resultType="studentModel">
        select name,age
        from student WHERE id=#{id}
    </select>

    <!--根据name和age查找数据集合-->
    <select id="queryList" parameterType="studentModel" resultType="studentModel">
        select name,age
        from student WHERE name=#{name} AND age=#{age}
    </select>

    <!--根据id更新-->
    <update id="update" parameterType="studentModel">
        UPDATE student set name = #{name},age=#{age} WHERE id = #{id}
    </update>

    <!--根据id删除-->
    <delete id="delete" parameterType="studentModel">
        DELETE from student WHERE id = #{id}
    </delete>
</mapper>

四,创建MyBatis的配置文件

在resources/mapper目录下创建MyBatis框架的配置文件,起名为sqlMapConfig.xml。在该文件中配置数据库参数,配置mapper文件,声明Model类对应的别名。内容如下:

<?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>
    <!--别名-->
    <typeAliases>
        <typeAlias type="com.honor.mybatis.model.StudentModel" alias="studentModel"/>
    </typeAliases>

    <!--配置数据库参数-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/xia?useUnicode=true&amp;autoReconnect=true&amp;characterEncoding=utf-8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置mapper文件-->
    <mappers>
        <mapper resource="mapper/studentMapper.xml"/>
    </mappers>

</configuration>

五,获取SqlSession对象

MyBatis框架操作数据库使用SqlSession对象,类似与hibernate框架中的Session对象。下面创建一个工具类,加载MyBatis的配置文件得到SqlSession对象。具体代码如下:

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        InputStream inputStream  = null;
        try {
            //加载MyBatis的配置文件SqlMapConfig.xml
            inputStream = Resources.getResourceAsStream("conf/SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //根据mybatis的配置文件创建SqlSessionFactory
         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    /**
     * 获取sqlSession对象
     * @return
     */
    public static SqlSession getSqlSession() {
        //根据SqlSessionFactory创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

六,插入操作

得到SqlSession对象即可以进行增删改查操作。插入操作代码如下:

    public static int  insertStudent(StudentModel student) {
        try {
            //1,得到sqlSession对象,
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //2,插入数据
            //第一个参数statement:指定mapper映射文件中statement的id。student对应mapper文件中的namespace,insert对应mapper中的id
            //第二个参数parameter,指定 输入参数
            sqlSession.insert("student.insert",student);
            //提交事务。注意:不提交也不报错,到数据库中没有数据
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            return student.getId();//返回插入后的id
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

解释:

  1. sqlSession对象中封装了数据库的地址账号和密码,所以可以操作数据库。
  2. 使用sqlSession的insert方法插入数据,insert方法中的参数很重要,具体参见代码中的注释。
  3. 此时执行的sql语句对应的是studentMapper.xml文件中的<insert id="insert">语句。

七,根据id查找单个对象

    public static StudentModel queryOne(int id) {
        try {
            //1,得到sqlSession对象,
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //2,查找一个数据
            StudentModel studentModel = sqlSession.selectOne("student.queryOne", id);
            //提交事务。
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            return studentModel;//返回StudentMdoel对象
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

注:1,测试使用sqlSession对象的selectOne方法。

       2,直接返回对象。

八,根据其他条件得到对象集合

  public static List<StudentModel> queryList(StudentModel student) {
        try {
            //1,得到sqlSession对象,
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //2,得到数据结合
            List<StudentModel> studentModelList = sqlSession.selectList("student.queryList", student);
            //提交事务。
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            return studentModelList;//返回对象集合
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

注:1,测试使用sqlSession对象的selectList方法。

       2,直接返回对象集合。

九,更新操作

    public static void update(StudentModel student) {
        try {
            //1,得到sqlSession对象,
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //2,得到数据结合
            sqlSession.update("student.update", student);
            //提交事务。
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

十,删除操作

    public static void delete(int id) {
        try {
            //1,得到sqlSession对象,
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            //2,删除
            sqlSession.delete("student.delete", id);
            //提交事务。
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

##总结

##MyBatis框架的使用步骤

  1. 添加mysql驱动和mybatis依赖。
  2. 创建Model类,此类字段与数据库表对应。
  3. 创建Mapper文件,此文件中写sql语句。
  4. 创建MyBatis框架的配置文件sqlMapConfig.xml,在配置文件中配置数据库参数和Mapper文件。

##Mapper文件

这是MyBatis的核心文件,操作数据库的sql语句写在该文件中。

理论上说一个Mapper文件中可以写任何sql语句,可以操作任何数据库表,但习惯一个Mapper文件对应一个数据库表。

Mapper中的sql语句不仅支持但表操作,也支持多表操作。任何sql语句都可以放入到Mapper文件中执行。

Mapper文件还可以实现动态sql,具体参见下一篇博客:MyBatis的使用详解。

##MyBatis与Hibernate对比

MyBatis的优点:灵活使用sql语句。

MyBatis的缺点:无。

猜你喜欢

转载自blog.csdn.net/fightingXia/article/details/82082242
今日推荐