MyBatis 学习笔记(一)MyBatis的简介与使用以及与其他ORM框架的比较

什么是MyBatis

MyBatis 前身是Apache基金会的开源项目iBatis,在2010年该项目脱离Apache基金会并正式更名为MyBatis,在2013年11月,MyBatis迁移到了GitHub。
MyBatis 是一个轻量级的,半自动的持久化(ORM)框架, 其通过XML映射配置文件或者注解来配置和映射原生类型,接口和Java的POJO(Plain Old Java Objects,普通老式Java对象)为数据库中的记录。之所以是半自动化的框架,是因为其不能像Hibernate一样实现自动生成SQL,其需要用户手动编写SQL语句。方便用户对SQL语句进行优化,适用于大数据量,高并发场景。
MyBatis 是一块比较容易上手的框架,使用者只需要通过简单的学习即可掌握其常用特性。

为什么要使用MyBatis

使用MyBatis访问数据库

首先在pom文件中引入依赖

       <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

正如前面所说MyBatis 是一个半自动持久化框架。所以,需要我们自己来维护sql 语句,编写sql语句的xml文件叫做映射文件。在此处,我建立了一个StudentMapper.xml 文件来维护sql 语句。

<mapper namespace="com.jay.mapper.StudentMapper">
    <resultMap id="BaseColumn" type="com.jay.entity.Student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>
     <select id="selectByName" resultMap="BaseColumn">
        select id,name,age from student where name LIKE '%'#{name}'%'
    </select>
</mapper>

上面的sql语句表示的意思是通过学生名称来模糊匹配学生

public interface StudentMapper {

    /**
     * @param name
     * @return
     */
    List<Student> selectByName(@Param("name") String name);
}

维护完映射文件和对应的接口之后,我们还需要一个XML配置文件来对MyBatis进行一些核心设置,包括获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)以及SQL映射文件的位置信息等。本节所使用的配置如下:

<configuration>
    <!--加载配置文件->jdbc.properties 数据库文件 -->
    <properties resource="jdbc.properties"/>

    <!-- 设置一个默认的连接环境信息 -->
    <environments default="development">

        <!--连接环境信息,取一个任意唯一的名字 -->
        <environment id="development">
            <!-- mybatis使用jdbc事务管理方式 -->
            <transactionManager type="JDBC"/>
            <!-- mybatis使用连接池方式来获取连接 -->
            <dataSource type="POOLED">
                <!-- 配置与数据库交互的4个必要属性 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
        
    </environments>

    <!-- 加载映射文件-->
    <mappers>
        <mapper resource="xml/StudentMapper.xml"/>
    </mappers>
</configuration>

到此,MyBatis所需的环境就配置好了,接下来我们将MyBatis跑起来。测试代码如下

    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void setUp() {
        String resource = "chapter1/mybatis-cfg.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, "development");
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void mybatisTest() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.selectByName("点点");
        if (studentList != null) {
            System.out.println("----->"+studentList.get(0).toString());
        }
        sqlSession.commit();
        sqlSession.close();
    }

如上测试代码,首先,我们根据配置文件得到文件流,然后通过SqlSessionFactoryBuilder工厂类构造器得到SqlSessionFactory,再通过SqlSessionFactory工厂类得到SqlSession。然后根据SqlSession的getMapper()方法得到需要执行的mapper。得到之后调用相应的方法得到结果。
运行结果如下:
在这里插入图片描述

使用JDBC访问数据库

现在我们使用原生的JDBC来操作数据库,主要流程有以下几个:1. 加载数据库驱动,2. 连接数据库,3,通过PreparedStatement执行sql得到ResultSet,4,对ResultSet 进行处理。流程固定。

public class JdbcTest {
    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mybatisdemo";
        String userName = "root";
        String password = "admin";

        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);

            String sql = "select id,name,age from student where name LIKE ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, "%点点%");
            resultSet = statement.executeQuery();
            List<Student> studentList = new ArrayList<Student>();
            if (resultSet != null) {
                while (resultSet.next()) {
                    Student student = new Student();
                    student.setId(resultSet.getInt("id"));
                    student.setName(resultSet.getString("name"));
                    student.setAge(resultSet.getInt("age"));
                    studentList.add(student);
                }
            }
  			System.out.println("----->执行的sql={}"+sql);
            System.out.println("----->resultSet={}"+studentList.get(0).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();

                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

代码比较简单,执行结果如下:

。。。。。。。。。。。。。。。。。


版权原因,完整文章,请参考如下:

MyBatis 学习笔记(一)MyBatis的简介与使用以及与其他ORM框架的比较

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值