Mybatis 基础教程

依赖引入

mybatis 目前最新的版本为mybatis3.如需使用mybatis,maven项目中需引入mybatis的依赖:

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

然后需要引入相关的驱动:

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

mybatis配置

xml配置

配置

如果使用xml配置作为你的配置,一般的格式是这样的:
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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/world_x?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;useLegacyDatetimeCode=false&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/yin/mybatis/mapper/CountryMapper.xml"/>
    </mappers>
</configuration>

CountryMapper.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="org.mybatis.mapper.CountryMapper">
    <select id="selectCountry" resultType="org.mybatis.bean.Country">
        select * from country where code = #{code}
    </select>
</mapper>

上述配置中mybatis-config.xml配置了数据库连接和事务管理器。同时导入了一个CountryMapper.xml的配置文件。该配置文件中配置了一条根据code做为条件查询country表的一条记录。

上述的工作完成之后,我们需要创建相关的对象与接口,如下分别是对应的代码:
Country.java


import lombok.Data;

@Data
public class Country {
    private String code;
    private String name;
    private String continent;
    private String region;
    private String surfacearea;
    private String indepyear;
    private String population;
    private String lifeexpectancy;
    private String gnp;
    private String gnpold;
    private String localname;
    private String governmentform;
    private String headofstate;
    private String capital;
    private String code2;
}

启动mybatis并进行数据库操作

配置完成之后,需要程序加载配置并实例化一个SqlSession来进行数据库的操作:

        InputStream inputStream = Resources.getResourceAsStream("org/mybatis/mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Country country = sqlSession.selectOne("org.mybatis.mapper.CountryMapper.selectCountry", "CHN");
        System.out.println(country);
        sqlSession.close();

通过上面的步骤,我们就加载了配置文件,并且可以调用对应的namespace,传递相关的参数查询出结果并进行封装。
同样,如果我们保持namespace同类名一致,sqlid同方法名一致时,我们可以直接通过java接口的方式进行调用:
CountryMapper.java

import org.mybatis.bean.Country;

public interface CountryMapper {
    Country selectCountry(String code);
}

调用的代码如下:

        CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
        System.out.println(countryMapper.selectCountry("CHN"));

这段代码同样可以完成查询,但不需要指定namespace,可以避免在编码时写错namespace导致的错误。

通过java的方式进行配置

上面的mybatis-config.xml配置的方式也可以用java的方式进行配置,配置的代码如下:

PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
        Properties properties = new Properties();
        properties.setProperty("driver", "com.mysql.cj.jdbc.Driver");
        properties.setProperty("url", "jdbc:mysql://localhost:3306/world_x?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=GMT");
        properties.setProperty("username", "root");
        properties.setProperty("password", "root");
        pooledDataSourceFactory.setProperties(properties);

        DataSource dataSource = pooledDataSourceFactory.getDataSource();

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);

        Configuration configuration = new Configuration(environment);
        configuration.addMapper(CountryMapper.class);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

通过这种方式可以在完全没有配置文件的情况下实现mybatis的配置。
但这里需要注意的是,CoutryMapper.xml必须和CoutryMapper.java目录保持一致。这样才能保证可以映射到对应的xml文件。
当然,如果你不希望使用xml作为sql的配置,上述例子你也可以使用注解的方式进行sql的配置:

package org.mybatis.mapper;

import org.apache.ibatis.annotations.Select;
import org.mybatis.bean.Country;

public interface CountryMapper {

    @Select("select * from country where code = #{code}")
    Country selectCountry(String code);
}

当然,两者也是可以共存的。这个视各项目情况和场景而定。

相关对象的作用域和生命周期

从上面的mybatis启动我们可以知道,mybatis在启动时会产生三个对象:SqlSessionFactoryBuilder、SqlSessionFactory和SqlSession。这三个对象分别负责加载配置,创建Sqlsession和进行数据库操作。接下来就说一下这三个对象的生命周期。

SqlSessionFactoryBuilder

该对象负责读取配置,并根据配置信息生成SqlSessionFactory对象,该对象应该在SqlSessionFactory对象生成之后销毁。

SqlSessionFactory

该对象负责生成SqlSession,SqlSession主要用来进行数据库的读写操作并负责事务管理。所以SqlSessionFactory应该存在于应用的整个运行过程当中。

SqlSession

该对象主要用来进行数据库的读写操作并负责事务管理。所以该对象作用时间应该是一次会话期间(单次请求的过程中)。会话处理结束时应该调用它的close()方法关闭连接并释放资源。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值